javascript - 在 JavaScript 比较中应该使用哪个等号运算符(== vs ===)?

标签 javascript operators equality equality-operator identity-operator

<分区>

我正在使用 JSLint通过 JavaScript,它返回许多建议,在比较 时用 === (三个等号)替换 == (两个等号) idSele_UNVEHtype.value.length == 0if 语句中。

== 替换为 === 是否有性能优势?

任何性能改进都将受到欢迎,因为存在许多比较运算符。

如果不进行类型转换,是否会比 == 有性能提升?

最佳答案

严格相等运算符 (===) 的行为与抽象相等运算符 (==) 相同,只是不进行类型转换,并且类型必须是相同被认为是平等的。

引用:Javascript Tutorial: Comparison Operators

== 运算符将在进行任何必要的类型转换后比较是否相等=== 运算符将 进行转换,因此如果两个值的类型不同,=== 将简单地返回 错误。两者都同样快。

引用 Douglas Crockford 的优秀 JavaScript: The Good Parts ,

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true

Equality Comparison Table

The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.


更新:

@Casebash 提出了一个很好的观点在评论和 @Phillipe Laybaert'sanswer关于对象。对于对象,===== 彼此一致(特殊情况除外)。

var a = [1,2,3];
var b = [1,2,3];

var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };

var e = "text";
var f = "te" + "xt";

a == b            // false
a === b           // false

c == d            // false
c === d           // false

e == f            // true
e === f           // true

特殊情况是当您将一个基元与一个计算结果为相同基元的对象进行比较时,由于其 toStringvalueOf 方法。例如,考虑将字符串基元与使用 String 构造函数创建的字符串对象进行比较。

"abc" == new String("abc")    // true
"abc" === new String("abc")   // false

这里 == 运算符检查两个对象的值并返回 true,但是 === 看到它们不是同一类型并返回 false。哪一个是正确的?这实际上取决于您要比较的内容。我的建议是完全绕过这个问题,只是不要使用 String 构造函数从字符串文字创建字符串对象。

引用
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

关于javascript - 在 JavaScript 比较中应该使用哪个等号运算符(== vs ===)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4025771/

相关文章:

javascript - == 和 != 已经变成不好的做法了吗?

javascript - 在加载@font-face-font 之前如何等待第一次 Canvas 重绘?

javascript - 在 Firefox 中访问 FileReader 的部分结果

javascript - 有没有办法改变默认警报窗口的外观和感觉

javascript - Jquery - if 语句中的运算符

java - kotlin 结构相等性检查父类(super class)型吗?

Java赋值运算符

javascript - 在特定属性值上使用 jQuery 切换(隐藏/显示)<td>

java - "x = x++"之后的 x 是什么?

带有赋值的java运算符优先级