Javascript中的空格是否等于整数0? [英] Is whitespace equals to integer 0 in Javascript?

查看:114
本文介绍了Javascript中的空格是否等于整数0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序行为异常,并认为下面的代码会意外地发出其他声明。

My app behaves abnormally and figured the code below is going to else statement unexpectedly.

代码

if(" " != 0) {
    console.log("whitespace is not zero");
}
else {
    console.log("bar");
}

Firebug输出

bar

我以为空白是一个字符串,与整数零的比较应该像上面的情况一样返回false,但我不知道为什么它会转到else语句。

I thought whitespace is a String and comparison against integer zero should return false like the case above but I don't know why it is going to else statement.

有人可以解释为什么吗? / p>

Could anyone explain why?

推荐答案

在JS中,== 0 等于 true 宽松/宽松比较,您应该使用严格相等运算符 === / !== 而不是:

In JS, " " == 0 equals true with loose/lenient comparison, you should use strict equality operator ===/!== instead:

" " !== 0

获得第一个条件。

测试:

console.log(" " == 0); // true
console.log(" " === 0); // false






宽松比较表:

""           ==   "0"           // false
0            ==   ""            // true
0            ==   "0"           // true
false        ==   "false"       // false
false        ==   "0"           // true
false        ==   undefined     // false
false        ==   null          // false
null         ==   undefined     // true
" \t\r\n"    ==   0             // true

严格比较图表:

""           ===   "0"           // false
0            ===   ""            // false
0            ===   "0"           // false
false        ===   "false"       // false
false        ===   "0"           // false
false        ===   undefined     // false
false        ===   null          // false
null         ===   undefined     // false
" \t\r\n"    ===   0             // false

(Douglas Crockford的例子)

(Examples by Douglas Crockford)

良好做法:

尽可能使用严​​格相等运算符,因为使用松散相等运算符,JS执行类型强制,这是性能命中并且不会总是产生预期的结果,如上面的比较图表所示。

Whenever possible, use strict equality operator because with loose equality operator, JS does type coercion which is a performance hit and doesn't always yield expected results as shown in above comparison charts.

这篇关于Javascript中的空格是否等于整数0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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