为什么x = 0相当于x =''[重复]

问题描述 投票:-2回答:4

这个问题在这里已有答案:

我很难过为什么不根据下面的代码调用下面的console.log。 x当然不等于'',因为它被设置为0

var x=0;

if (x!=''){
  console.log('here', x);
}
javascript
4个回答
0
投票

你需要使用!==而不是!=

var x = 0;

if (x !== ''){
  console.log('here', x);
}

同样适用于===而不是==

这是因为三等于也检查类型,否则值被强制变为“真实”或“假”值。

console.log(0 == '');   //>true
console.log(0 === '');  //>false
console.log(3 == '3');  //>true
console.log(3 === '3'); //>false

0
投票

这是一篇很好的文章,解释了JavaScript中的“真实性”和“虚假性”:

https://j11y.io/javascript/truthy-falsey/

要解决它,请使用严格的比较,!==和===。


0
投票

这是因为0是一个假值(https://developer.mozilla.org/en-US/docs/Glossary/Falsy

if (0) console.log("hi, I'm a falsy value)

如果你想检查确切的类型和值,请尝试===运算符

if (x === 0) console.log("zero here)

0
投票

这是因为你正在使用Loose Equality

在将两个值转换为公共类型之后,松散相等性将两个值相等。转换后(一方或双方可能进行转换),最终的相等比较完全按照===执行它。

==将操作数转换为普通类型。在这里0Number所以它将''转换为Number使用Number('')Number('')返回0所以这就是为什么0 == ''。 如果你想避免这种情况,你可以使用===!==

console.log(Number(''))//0

var x = 0;
if (x !== ''){
  console.log('here', x);
}
© www.soinside.com 2019 - 2024. All rights reserved.