为什么在比较String时使用===而不是==

时间:2013-03-26 19:25:22

标签: javascript jquery

检查String值时,我使用'=='。但我见过使用'==='的情况。例如,而不是

if("true" == "true"){
 alert('true');
}

使用:

if("true" === "true"){
 alert('true');
}

这背后的原因是什么?这两个用例似乎都按预期工作。

4 个答案:

答案 0 :(得分:8)

===运算符确保不仅值相等,而且被比较的两个项也是相同的类型;而==运算符仅检查两个项的值是否相等

正如@amnotiam在评论中提到的那样,您可能还想查看The Abstract Equality Comparison Algorithm

答案 1 :(得分:4)

10 == '10'  // true  | check value: 10 equal 10
10 == 10    // true  | check value: 10 equal 10

10 === '10' // false | check type: int not equal string
10 === 10   // true  | check type: int equal int, check value: 10 equal 10

检查类型与否。

答案 2 :(得分:3)

===用于检查类型为..的值。

var str="300";

//this gt execute
if(str==="300")
{
        alert("this alert get executed");
}


//this not execute
if(str===300)
{
        alert("this alert not get executed");    
}

对于==下面的//this get execute if(str=="300") { alert("this alert get executed"); } //this get execute if(str==300) { alert("this alert get executed"); } ,两个代码都有效,因为它不检查类型

{{1}}

答案 3 :(得分:1)

第一次检查只是一个逻辑测试,第二次检查是逻辑测试和类型测试。

==检查一侧是否等于第二个,而===检查左侧是否等于第二个但是来自同一类型。

if("true" == "true")

检查两者是否是相同的字符串

if("true" === "true")

检查两者是否都是相同的字符串,两者都是字符串值。

另请注意,有一个!==运算符,它执行负值和类型比较。