Frage

Today my friends sent my some code that did something unexpected:

setTimeout(["console.log(1", "2)"], 1000)

I expected this to fail or do some magic, but it just prints 1 2 after 1 second. I can see it possibly evaluating the array to "console.log(1,2)" using a simple array.join(','), but why does that happen?

I've looked into the eval capabilities of setTimeout, but it should only do a function or a string. The use of an array here doesn't make any sense, and searching Google for why this does work turns up nothing, or even close use cases.

War es hilfreich?

Lösung

setTimeout can evaluate a string as javascript, if the value is not a function it will then convert the value to a string, probably by using toString()

You can see if you do this

"" + ["console.log(1", "2)"]

or

["console.log(1", "2)"].toString();

you get

'console.log(1,2)'

Then it get's evaluated accordingly

Andere Tipps

If it is not a function then it uses .toString() to get a string value.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top