我使用JSLint通过JavaScript,它返回了许多建议,以取代 ==(两个平等的标志)与 ===(三个平等的标志)当做一些事情,如比较idSele_UNVEHtype.value.length == 0在一个假设声明。

能否取代 = = = = = = =?

任何性能改进都将被欢迎,因为有许多比较运营商。

如果没有类型转换发生,会有超越 ==的性能收益吗?


当前回答

原因在上面的答案中被解释,而且杜格拉斯·克罗克福德也对此非常清楚(JavaScript:The Good Parts)。

但是,有一個例外: == null 是檢查“是零或不定義”的有效方式:

if( value == null ){
    // value is either null or undefined
}

例如,jQuery 1.9.1 使用此模式 43 次,而 JSHint 合成检查器甚至为此提供 eqnull 放松选项。

从 jQuery 风格指南:

严格的平等检查(===)应用于对 ==的支持,唯一的例外是通过零来检查非定义和零。

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

编辑 2021-03:

如今,大多数浏览器支持 Nullish coalescing 操作器(??) 和 Logical nullish 任务(??=),如果变量是 null 或 undefined,例如:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

可以用任何形式写作。

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;

其他回答

在PHP和JavaScript中,它是一个严格的平等运营商,这意味着它将比较类型和值。

=== 运营商检查值以及变量的类型,以便平等。

操作员只检查平等变量的值。

原因在上面的答案中被解释,而且杜格拉斯·克罗克福德也对此非常清楚(JavaScript:The Good Parts)。

但是,有一個例外: == null 是檢查“是零或不定義”的有效方式:

if( value == null ){
    // value is either null or undefined
}

例如,jQuery 1.9.1 使用此模式 43 次,而 JSHint 合成检查器甚至为此提供 eqnull 放松选项。

从 jQuery 风格指南:

严格的平等检查(===)应用于对 ==的支持,唯一的例外是通过零来检查非定义和零。

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

编辑 2021-03:

如今,大多数浏览器支持 Nullish coalescing 操作器(??) 和 Logical nullish 任务(??=),如果变量是 null 或 undefined,例如:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

可以用任何形式写作。

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;

我在Firefox使用Firebug测试了此类代码:

console.time(“testEquality”); var n = 0; while (true) { n++; if (n == 100000) break; } console.timeEnd(“testEquality”);

console.time(“testTypeEquality”); var n = 0; while (true) { n++; if (n === 100000) break; } console.timeEnd(“testTypeEquality”);

我的结果(每次测试5次,平均):

==: 115.2
===: 114.4

所以我会说小差异(这是超过100000 iterations,记住)是不可忽视的。 性能不是一个理由做 ===. 类型安全(好,安全,你会得到在JavaScript),和代码质量是。

意思是平等 没有类型强制性 类型强制性 意思是 JavaScript 不会自动将任何其他数据类型转换为序列数据类型

0==false   // true,although they are different types

0===false  // false,as they are different types

2=='2'    //true,different types,one is string and another is integer but 
            javaScript convert 2 to string by using == operator 

2==='2'  //false because by using === operator ,javaScript do not convert 
           integer to string 

2===2   //true because both have same value and same types