在Javascript中解释为什么'+ [] == 0'输出'true'? [英] Explain why '+[] == 0' output 'true' in Javascript?

查看:111
本文介绍了在Javascript中解释为什么'+ [] == 0'输出'true'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解释为什么 + [] == 0 在Javascript中输出'true'

Explain why +[] == 0 give output 'true' in Javascript?

请检查示例。

+[] == 0 ? alert(true) : alert(false);

并检查。
'1 + [+ []]'输出 '10'

推荐答案

它将按如下方式进行评估,

It will be evaluated like below,

1: + [] == 0 - > +== 0

运营商 + 正在最高优先级而不是 == 所以它将首先进行评估。因此,在将数组转换为数字时, ToPrimitive() 函数将通过将其作为参数传递来调用。由于 [] 是一个对象,它将返回字符串

Operator + is having highest priority than == so it will be evaluated first. So during the conversion of an array to number, ToPrimitive() function will be called by passing it as an argument. Since [] is an object, it will return "" string

2: +== 0 - - > 0 == 0

2 : +"" == 0 --> 0 == 0

空字符串将转换为 0 。如我们所知,非空字符串将转换为 NaN

An empty string will be converted to 0. And a non-empty string would be converted to NaN as we all know.

3: 0 == 0 - > true

最后根据摘要等式比较算法,当两个相同类型的操作数进行比较时,不会进行进一步的评估,它将直接检查其相等性并返回结果。

And finally as per abstract equality comparison algorithm, when both operands of same type getting compared, no further evaluation will happen, it will directly checks for its equality and return the result.

在第二种情况下 1 + [+ []] ,评估将会发生,

And in your second case 1+[+[]], evaluation will happen like,

1: 1 + [+ []] - ( [] 它是一个对象

1 : 1+[+[]] - ( +[] will be converted to primitive first since [] it is an object)

2: 1 + [+] toPrimitive([])

2 : 1+[+""] ( toPrimitive([]) will be "" )

3: 1+ [0] 0 将在您转换时产生空字符串编号

3 : 1+[0] ( 0 will be yielded when you convert an empty string to number )

4: 1+0 toPrimitive([0] ) 0

4 : 1+"0" ( toPrimitive([0]) will be "0" )

5: 10

这篇关于在Javascript中解释为什么'+ [] == 0'输出'true'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆