javascript comparison crises

半世苍凉 提交于 2019-12-23 12:53:32

问题


I came across the following and was unable to grasp the reason, can anyone explain please?

var foo = [0];
console.log(foo == !foo); // true 
console.log(foo == foo);  // true

回答1:


The second comparison is simple to explain: foo is equal to itself.

The first one, however, is a bit tricky: foo is an array, which is an object, which evaluates to true when coerced to boolean. So !foo is false. But foo on the left side of the comparison is not being converted to boolean. Both operands are actually converted to numbers during the equality comparison. This is how it evaluates:

[0] == false
[0] == 0
"0" == 0
0 == 0
true

According to MDN, on comparisons with the equality operator ==:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible

I know this explanation sounds superficial. It's actually much more complicated than that, but the basic steps are the ones I listed above. You can see the details on the ECMA-262 specification, particularly on sections 9 and 11.9.




回答2:


You should use "===" and "!==" instead of "==" and "!=" More explanations there: Which equals operator (== vs ===) should be used in JavaScript comparisons?

http://net.tutsplus.com/tutorials/javascript-ajax/the-10-javascript-mistakes-youre-making/



来源:https://stackoverflow.com/questions/12753646/javascript-comparison-crises

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