Explain why '+[] == 0' output 'true' in Javascript?
This question already has an answer here:
It will be evaluated like below,
1 : +[] == 0
--> +"" == 0
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
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.
And in your second case 1+[+[]]
, evaluation will happen like,
1 : 1+[+[]]
- ( +[]
will be converted to primitive first since []
it is an object)
2 : 1+[+""]
( toPrimitive([])
will be ""
)
3 : 1+[0]
( 0
will be yielded when you convert an empty string to number )
4 : 1+"0"
( toPrimitive([0])
will be "0"
)
5 : "10"
JavaScript evaluates +[] == 0
this way:
+ []
: +
operator tries to convert the operand []
to a primitive value. + []
: []
is transformed to a string using toString()
method, which is an alias for [].join(',')
. The result is an empty string ''
+ ''
: the empty string is transformed to a number: Number('')
-> 0
+ 0
becomes 0
+[] == 0
-> 0 == 0
-> true
The '1+[+[]]'
evaluation:
1 + [ +[] ]
(Transform []
into a primitive: ''
) 1 + [ + '' ]
(Transform ''
into a number: 0
) 1 + [ + 0 ]
( + 0
is 0
) 1 + [ 0 ]
(Addition operator forces the transform of [0]
into a primitive value: [0].toString()
-> [0].join(',')
-> '0'
) 1 + '0'
(Because the second operand '0'
is a string, transform the first number 1
to a string too: '1'
) '1' + '0'
(Simple strings concatenation) '10'
Read also this article about the addition operator.
链接地址: http://www.djcxy.com/p/48046.html