console.log( 0 == '0' ); // true
console.log( 0 == [] ); // true
console.log( [] == '0' ); // falseRun Code Online (Sandbox Code Playgroud)
为什么JavaScript会像这样评估表达式?
Jam*_*iec 24
简而言之,数字0是假的,字符串"0"不是.
但是,JavaScript会在使用double equals时尝试强制类型.所以你从中得到了真实
console.log( 0 == '0'); // true
Run Code Online (Sandbox Code Playgroud)
因为JavaScript强迫数字.
下一个:
console.log( 0 == [] ); // true
Run Code Online (Sandbox Code Playgroud)
这有点令人困惑,因为空数组是真实的,零是假的.但是,如果你将一个空数组强制转换为一个数字,你得到它的长度 - 这是零.所以这个实际上是0 == 0在对数字进行评估之后进行评估.
有了这个:
console.log( [] == '0'); // false
Run Code Online (Sandbox Code Playgroud)
JavaScript不能将它们强制转换为相同的类型 - 而另一种则是伪造的,而另一种则不是.
总而言之,这就是为什么使用三等于一般更安全,它检查类型和相等.
下面一个方便的例证
function truthyOrFalsy(val) {
return val ? "Truthy" : "Falsy";
}
console.log("empty array:", truthyOrFalsy([]));
console.log("number zeroL", truthyOrFalsy(0));
console.log("string with a zero character:", truthyOrFalsy("0"));Run Code Online (Sandbox Code Playgroud)
小智 7
/*
If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y).
*/
console.log( 0 == '0');
/*
If Type(x) is either String or Number and Type(y) is Object,
return the result of the comparison x == ToPrimitive(y).
*/
console.log( 0 == [] );
/*
If Type(x) is Object and Type(y) is either String or Number,
return the result of the comparison ToPrimitive(x) == y.
*/
console.log( [] == '0');
Run Code Online (Sandbox Code Playgroud)
来源:http://es5.github.io/#x11.9.3
小智 5
Truthy和Falsy除类型外,每个值还具有一个固有的布尔值,通常称为True或Falsy。有些规则有些奇怪,因此在调试JavaScript应用程序时理解概念和比较效果会很有帮助。
以下值始终是虚假的:
其他一切都是真实的。那包括:
使用==松散相等性比较真实值和虚假值时,可能会发生意外情况:
参见平等宽松比较表