Possible Duplicate:
Implied string comparison, 0='', but 1='1'
在 JavaScript 中执行以下情况,我得到 0 等于 ''(空字符串)
var a = 0;
var b = '';//empty string
if(a==b){
console.log('equal');//this is printed in console
}else{
console.log('not equal');
}
谁能指导一下这背后的原因是什么?
最佳答案
引用文档(MDN):
Equal (==)
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; else if either operand is a string, the other operand is converted to a string if possible.
由于这里的a
操作数类型是Number
,所以b
也会转换为Number。 Number('')
的计算结果为 0
。
有时这会让人感到非常惊讶。例如考虑一下:
console.log(0 == '0'); // true
console.log(0 == ''); // true
console.log('' == '0'); // O'RLY?
...或者这个:
console.log(false == undefined); // false
console.log(false == null); // false
console.log(null == undefined); // fal.... NO WAIT!
...这正是为什么几乎总是建议使用 ===
(严格相等)运算符的原因。
关于javascript - 为什么javascript将0视为空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422064/