문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top