JavaScript if(x)与if(x == true) [英] JavaScript if(x) vs if(x==true)

查看:51
本文介绍了JavaScript if(x)与if(x == true)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,在以下情况下,以下语句在逻辑上不相等?

In JavaScript , in which cases the following statements won't be logically equal ?

if(x){}

if(x==true){}

谢谢

推荐答案

它们根本不相等.

if (x)

检查 x 是否为Truthy,稍后检查 x 的布尔值是否为 true .

checks if x is Truthy where as the later checks if the Boolean value of x is true.

例如,

var x = {};
if (x) {
    console.log("Truthy");
}
if (x == true) {
    console.log("Equal to true");
}

不仅对象,任何字符串(空字符串除外),任何数字( 0 除外(因为 0 为Falsy)和 1 )将被视为Truthy,但它们将不等于true.

Not only an object, any string (except an empty string), any number (except 0 (because 0 is Falsy) and 1) will be considered as Truthy, but they will not be equal to true.

根据 ECMA 5.1标准,在 if(x)中,<将根据下表确定code> x

+-----------------------------------------------------------------------+
| Argument Type | Result                                                |
|:--------------|------------------------------------------------------:|
| Undefined     | false                                                 |
|---------------|-------------------------------------------------------|
| Null          | false                                                 |
|---------------|-------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number        | The result is false if the argument is +0, −0, or NaN;|
|               | otherwise the result is true.                         |
|---------------|-------------------------------------------------------|
| String        | The result is false if the argument is the empty      |
|               | String (its length is zero); otherwise the result is  |
|               | true.                                                 |
|---------------|-------------------------------------------------------|
| Object        | true                                                  |
+-----------------------------------------------------------------------+

注意:最后一行 object ,其中包括对象和数组.

Note: The last line object, which includes both objects and Arrays.

但是在后一种情况下,根据抽象平等比较算法

But in the later case, as per The Abstract Equality Comparison Algorithm,

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

x

值将转换为数字,并将根据 true 对该数字进行检查.

注意:

在JavaScript中, true 1 ,而 false 0 .

In JavaScript, true is 1 and false is 0.

console.log(1 == true);
# true
console.log(0 == false);
# true

这篇关于JavaScript if(x)与if(x == true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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