带有字符串和索引的 JavaScript 类型强制转换 [英] JavaScript type coercion with strings and indexing
问题描述
在下面的代码片段中,为什么 whatDoesItDo()
函数将fail"作为字符串返回?如果有人能解释这种行为背后的概念会很有帮助.
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>
推荐答案
您将看到 A) 类型强制、B) 使用 []
索引到字符串和 C) 字符串连接的效果.
You're seeing the effects of A) Type coercion, B) Indexing into strings using []
, and C) String concatenation.
让我们看第一点:
(![] + [])[+[]]
![]
给了我们 false
因为 []
是一个真实"的值,它强制为 true
当测试为布尔值时,所以 ![]
是 false
.
![]
gives us false
because []
is a "truthy" value that coerces to true
when tested as a boolean, and so ![]
is false
.
然后我们将 []
添加到它,这会将它们都转换为字符串,因为 +
运算符将其两个参数强制转换为字符串,如果它们中的任何一个不是数字(如果两者都是数字,它会添加),给我们 "false"
(因为 [].toString()
是 [].join()
> 即 ""
).
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 ""
).
所以现在我们有了"false"
.
那么,+[]
是 0
因为它将空数组强制转换为一个数字,它通过一个字符串(""
),并且 +""
是 0
.
Then, +[]
is 0
because it coerces the empty array to a number, which takes it through being a string (""
), and +""
is 0
.
最后,该值用于 "false"
:"false"[0]
是 "f
".
Finally, that value is used on "false"
: "false"[0]
is "f
".
依此类推,其余的只是该主题的变体.(!+[]
是 true
,这在后面很重要.)
And so on, the rest of it is just variations on that theme. (!+[]
is true
, which matters later.)
这篇关于带有字符串和索引的 JavaScript 类型强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!