admin管理员组文章数量:1388868
I am trying to understand the significance of the following code in javascript:
alert(+[]);
Displays 0
Is there any name for this? What concepts are involved?
I am trying to understand the significance of the following code in javascript:
alert(+[]);
Displays 0
Is there any name for this? What concepts are involved?
Share Improve this question asked Apr 12, 2014 at 19:39 asim-ishaqasim-ishaq 2,2306 gold badges33 silver badges58 bronze badges 1- possible duplicate of Why is ++[[]][+[]]+[+[]] = "10"? – GSerg Commented Apr 12, 2014 at 19:55
1 Answer
Reset to default 9The plus in prefix position can only act on numbers, so it 'coerces' its argument to a number. The empty array is not a number and can't be directly turned into one, so it is first coerced to the string representation of it (same as .toString()) which is "", and then "" is coerced to a number which is defined to be zero. You could also do the same thing with +""
or +[0]
or +[[[["0"]]]]
. It's not just a plus, you can get a numeric coercion in a number of situations (most arithmetic operators), which will all treat [] as if it is 0.
You can get some messed up coercions involving arrays, because when they are converted to strings they do not have the square brackets around them so an array nested inside another array has the same string representation and hence ends up as the same number.
My standard example that I enjoy giving in these situations is [["\t\n 987654321e-432"]]
. Yes, that will coerce to the number 0 if you stick it in an arithmetic expression (e.g. if ([["\t\n 987654321e-432"]] == 0) {alert('strange huh?')}
), despite not having a zero in it anywhere. That's because the string inside the doubly nested array coerces to a valid number too small to be represented in a javascript number, so it gets rounded to 0. The fact that the string to number coercion also ignores initial whitespace is also shown.
本文标签: why a plus sign before array notation in javascript returns zeroStack Overflow
版权声明:本文标题:why a plus sign before array notation in javascript returns zero - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744627988a2616372.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论