为什么javascript会将0等于空字符串? [英] Why javascript treats 0 equal to empty string?
问题描述
可能重复:
隐含字符串比较,0 ='',但1 ='1'
在javascript中执行以下情况,我得到0等于''(一个空字符串)
var a = 0;
var b =''; //空字符串
if(a == b){
console.log('equal'); //这是打印在控制台
} else {
console.log('not equal');
}
任何人都可以指导这背后的原因是什么?
引用文档( MDN ):
等于(==) b
$ b如果两个操作数的类型不同,JavaScript会转换
操作数,然后应用严格比较。如果任一操作数是数字
或布尔值,则操作数被转换为数字(如果可能的话); else
如果任一操作数是一个字符串,另一个操作数转换为
字符串。
因为 a
操作数类型在这里是数字
, b
到数字。 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!
...这就是为什么几乎总是推荐使用 == =
(严格相等)运算符。
Possible Duplicate:
Implied string comparison, 0='', but 1='1'
Executing the following case in javascript, I get 0 equal to '' (an empty string)
var a = 0;
var b = '';//empty string
if(a==b){
console.log('equal');//this is printed in console
}else{
console.log('not equal');
}
Could anyone guide that what is the reason behind this?
Quoting the doc (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.
As a
operand type here is Number
, b
gets converted to Number as well. And Number('')
evaluates to 0
.
This can be quite surprising sometimes. Consider this, for example:
console.log(0 == '0'); // true
console.log(0 == ''); // true
console.log('' == '0'); // O'RLY?
... or this:
console.log(false == undefined); // false
console.log(false == null); // false
console.log(null == undefined); // fal.... NO WAIT!
...and that's exactly why it's almost always recommended to use ===
(strict equality) operator instead.
这篇关于为什么javascript会将0等于空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!