在JS if(condition)表示== true或=== true

时间:2013-07-26 14:14:31

标签: javascript css

我知道=====之间的区别但是我始终认为if (condition) condition应该使用严格相等来对true进行评估({ {1}})而不是类型强制相等(===)。

查看示例:

==

它返回:

if (1) {
    console.log("1");
}

if (1 == true) {
    console.log("2");
}

if (1 === true) {
    console.log("3");
}

我知道1并不严格等于::1 ::2 ,因为类型不同,但是根据W3C我做true时应该是严格的相等性测试(if (condition))运行不是===的类型强制相等。

那为什么要记录1?

9 个答案:

答案 0 :(得分:9)

if语句使用condition == true。它在ECMAScript语言规范中给出,这里:http://www.ecma-international.org/ecma-262/5.1/#sec-12.5

请注意步骤2中ToBoolean()的用法。这会将给定参数转换为布尔值,这意味着是,类型强制确实会发生if语句的条件。

答案 1 :(得分:5)

Javascript a.k.a. ECMAScript不受W3C管辖,但受ECMA管辖。您可以阅读规范here。您感兴趣的是this部分,它指定了如何处理if语句中的表达式。运行时应该在表达式值上调用toBoolean;意味着任何类型都将转换为布尔值。

因此它的行为类似于==

答案 2 :(得分:4)

因为===是严格的比较运算符。

if (1 === true) { //they are of a different type

你试过这个吗?

if (0) {  // This fails
    console.log("1");
}

因为0 = off, negative, no, false普遍存在。检查此Why is 0 false?

而当你使用===

if( 1 === true)  //It looks for type 1 as number and true as boolean

ES5 spec defines the following algorithm:

enter image description here

答案 3 :(得分:3)

它等同于condition == true,由ECMAScript语言规范

指定

答案 4 :(得分:3)

3个等号表示“没有类型强制的平等”。使用三等于,值也必须在类型上相等。

Difference between == and === in JavaScript

答案 5 :(得分:3)

当你从一本关于CSS的书中获得这些信息时,作者很可能会引用这样的CSS规则:

[if IE]body
{/* only for IE*/
    [if IE 6] background: url('get_real.gif');
    [if gt IE 6] background: url('nogood_browser.png');
}
[if Webkit]body
{/*Only webkit browsers get this bg*/
    background: url('webkit_bg.png');
}
[if Gecko]body
{/*Gecko-based browsers get this*/
   background: url('foxy.png');
}

除此之外 - 在JS上:

我的猜测是你有了from the place all mis-information comes from的想法。请为了你和我的don't use w3schools

如果if (condition) condition应该读expression是正确的,那么它应该是 truthy ,如果表达式由单个值组成。如果您要比较2个表达式,条件表达式将根据您比较两个操作数的方式计算为truefalse

单一操作数:

if (1)//truthy
if (undefined) //falsy

这是因为Boolean(1) === trueBoolean(undefined) === false
一旦引入第二个操作数:

if ('0' == 0)//=== true
if ('0' === 0)// === false

那是因为===是一个类型值检查,您显然已经知道了。就这样,没有混淆:

如果您想确保您拥有正确的信息:请检查ECMAScript语言规范,而不是某些第三方资源: here's the link

答案 6 :(得分:1)

Truthy:评价为TRUE的东西。 Falsey:评估为FALSE的东西。

1是真实的,0是假的。

任何类型的对象(包括函数,数组)总是很简单。

这些都是假的:undefined,null,NaN,0,“”(空字符串)和false。

因此,在您的第一个条件if (1)...记录1,因为1是真实的。

===专门测试类型相等,这与测试真相不同。

答案 7 :(得分:0)

我在ToBoolean上找到了ECMA文档中的部分,该部分在if语句中使用。

总结:

  

Number:如果参数为+ 0,-0或NaN,则结果为false;   否则结果是真的。

答案 8 :(得分:0)

注意:有一种将表达式转换为布尔值的简单方法,它正在使用!!运营商。例如,!! 1为真  !! {}是真的  !!“”是假的!!“asdf”是真的 所以我总是很乐意将表达式转换为布尔值,然后让它们进入if比较测试

if (1) { // !!1 is true and anything non-zero is true even -ve numbers just like c language
    console.log("1");
}

if (1 == true) { //!! 1 is true and we are not checking type only two equals (==)
    console.log("2");
}

if (1 === true) { //!! 1 is true but the type is number which is obviously not a Boolean type
    console.log("3");
}
相关问题