为什么javascript将0视为空字符串? [英] Why javascript treats 0 equal to empty string?

查看:58
本文介绍了为什么javascript将0视为空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
隐含字符串比较,0='',但 1='1'

在javascript中执行以下情况,我得到0等于''(空字符串)

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?

推荐答案

引用文档 (MDN):

等于 (==)

如果两个操作数的类型不同,JavaScript 会转换操作数然后应用严格的比较.如果任一操作数是数字或布尔值,如果可能,将操作数转换为数字;别的如果任一操作数是字符串,则另一个操作数将转换为如果可能,字符串.

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操作数类型是Numberb也被转换为Number.并且 Number('') 计算结果为 0.

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?

... 或者这个:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆