javascript - 为什么javascript将0视为空字符串?

标签 javascript if-statement comparison

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/

相关文章:

javascript - iOS 8 Beta 2 中的 Cordova 地理定位问题

algorithm - 每次按键后进行文本比较的工具/算法

java - 是否保证 new Integer(i) == i 在 Java 中?

c#如何判断两个对象是否相等

php - ajax 请求后,Syntaxhighlighter 找不到任何画笔

javascript - jQuery 文本节点对象到字符串

javascript - 过渡排序网页上显示的内容

java - 如何检查一个单词是否包含一个字母或一组字母?

java - 在 If 语句中比较字符串时出错

javascript - 我怎样才能最小化我的javascript函数?