JavaScript type coercion with strings and indexing

Deadly 提交于 2021-02-07 10:14:31

问题


In the below snippet why does whatDoesItDo() function return "fail" as string? It would be helpful if someone can explain the concept behind such behavior.

function whatDoesItDo() {

  return (![] + [])[+[]] + (![] + [])[+!+[]] +
    ([![]] + [][
      []
    ])[+!+[] + [+[]]] + (![] + [])[!+[] + !+[]];

}

function result() {

  document.getElementById("result").innerHTML = whatDoesItDo();

}

result();
<html>

<body>
  <p id="result"></p>
</body>

</html>

回答1:


You're seeing the effects of A) Type coercion, B) Indexing into strings using [], and C) String concatenation.

Let's look at the first bit:

(![] + [])[+[]]

![] gives us false because [] is a "truthy" value that coerces to true when tested as a boolean, and so ![] is false.

Then we add [] to it, which turns them both into strings because the + operator coerces both its arguments to strings if either of them isn't a number (if both are numbers, it adds), giving us "false" (because [].toString() is [].join() which is "").

So now we have "false".

Then, +[] is 0 because it coerces the empty array to a number, which takes it through being a string (""), and +"" is 0.

Finally, that value is used on "false": "false"[0] is "f".

And so on, the rest of it is just variations on that theme. (!+[] is true, which matters later.)



来源:https://stackoverflow.com/questions/30875019/javascript-type-coercion-with-strings-and-indexing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!