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

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

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

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


当前回答

简单

= = = = = = = = = = = = = = = = = = = = = =

=== 是指在没有类型强迫的情况下进行操作的比较。

格式强制在JavaScript中意味着自动将数据类型转换为其他数据类型。

例如:

123 == "123"  // Returns true, because JS coerces string "123" to number 123
              // and then goes on to compare `123 == 123`.

123 === "123" // Returns false, because JS does not coerce values of different types here.

其他回答

意思是平等 没有类型强制性 类型强制性 意思是 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 

它建议取代 ==与 ===的原因是 ===操作员比 ==更可靠。在我们的背景下可靠的手段 ===也去类型检查. 考虑到最好的编程做法,我们应该总是选择更可靠的功能比不可靠的一个。 再一次,每当我们想到的正是相同的操作员大部分时间,我们是默认考虑类型应该是相同的。

使用 = = 运营商(平等)

true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2;  //true, because "2" is converted to 2 and then compared

使用 === 运营商(身份)

true === 1; //false
"2" === 2;  //false

这是因为平等运营商 = = 输入强迫,这意味着翻译者在比较之前暗示地试图转换值。

另一方面,身份操作员 === 不做类型强制,因此在比较时不转换值。

原因在上面的答案中被解释,而且杜格拉斯·克罗克福德也对此非常清楚(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;

无,无,无,无,无,无。

var a;
var b = null;

在这里, a 和 b 没有值. 因为, 0 是虚假的和 '' 都是值. 其中的一件常见的是,它们都是虚假的值,这意味着它们都满足虚假的条件。

因此, 0 虚假和 '' 一起形成一个子组. 另一方面, null 和 undefined 形成第二个子组. 查看下图中的比较. null 和 undefined 将是相同的. 其他 3 将是相同的。

此分類上一篇

這是相同的任何物體(如 {}, arrys,等),不空的線 & Boolean 真實是所有真實的條件. 但,他們都不是平等。