为什么数组等于数组(javascript)?
Why Array is equal not array (javascript)?
我们都知道 JavaScript 是一种非常有趣的语言,其中包含棘手的部分。
请解释它是如何工作的,如果可能的话:[ ]
等于 ![ ]
.
[ ] == ![ ] // -> true
没看懂,为什么结果是"true"
?
当您调用 if (array == false) 时,您比较此对象的值和原始 false 值。在内部,调用 arr.toString(),其中 returns 一个空字符串 "".
![] // will return false
[] == false // this would return true, since "" == false
console.log((![]).toString());
console.log(([]).toString());
console.log("" == false);
内部是这样调用的,请查看this answer
更多详情
因为 ==
没有比较它们类型安全,但是值被强制转换:
[] == ![]
//is
[] == false
//is casted into
"" == false
//and that into
false == false
//wich is
true
使用类型安全比较
console.log(`[] == ![]`, [] == ![])
console.log(`[] === ![]`, [] === ![])
在我看来,使用 ==
的唯一原因是当您反对 null
或 undefined
并且想要涵盖两者时。所以,写作
value == null
//or
value != null
//instead of the more explicit (but longer)
value === null || value === undefined
//respectively
value !== null && value !== undefined
我会在其他任何地方使用 ===
,因为 ==
有时会出现这些有趣的结果。
这是一个关于该主题的有趣小片段,请欣赏:https://www.destroyallsoftware.com/talks/wat
我们都知道 JavaScript 是一种非常有趣的语言,其中包含棘手的部分。
请解释它是如何工作的,如果可能的话:[ ]
等于 ![ ]
.
[ ] == ![ ] // -> true
没看懂,为什么结果是"true"
?
当您调用 if (array == false) 时,您比较此对象的值和原始 false 值。在内部,调用 arr.toString(),其中 returns 一个空字符串 "".
![] // will return false
[] == false // this would return true, since "" == false
console.log((![]).toString());
console.log(([]).toString());
console.log("" == false);
内部是这样调用的,请查看this answer 更多详情
因为 ==
没有比较它们类型安全,但是值被强制转换:
[] == ![]
//is
[] == false
//is casted into
"" == false
//and that into
false == false
//wich is
true
使用类型安全比较
console.log(`[] == ![]`, [] == ![])
console.log(`[] === ![]`, [] === ![])
在我看来,使用 ==
的唯一原因是当您反对 null
或 undefined
并且想要涵盖两者时。所以,写作
value == null
//or
value != null
//instead of the more explicit (but longer)
value === null || value === undefined
//respectively
value !== null && value !== undefined
我会在其他任何地方使用 ===
,因为 ==
有时会出现这些有趣的结果。
这是一个关于该主题的有趣小片段,请欣赏:https://www.destroyallsoftware.com/talks/wat