我正在使用 JSLint通过 JavaScript,它返回了许多建议,在比较 时用
。===
(三个等号)替换 ==
(两个等号) if
语句中的 idSele_UNVEHtype.value.length == 0
将 ==
替换为 ===
是否有性能优势?
由于存在许多比较运算符,因此欢迎任何性能改进。
如果不进行类型转换,是否会比 ==
获得性能提升?
最佳答案
除了不进行类型转换,而且类型必须是相同被视为相等。
引用: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===
producestrue
and!==
producesfalse
. 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
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 producefalse
with the===
operator.
更新:
@Casebash 提出了一个很好的观点在评论和 @Phillipe Laybaert's answer关于对象。对于对象,==
和 ===
彼此一致(特殊情况除外)。
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
特殊情况是当您将一个基元与一个评估为相同基元的对象进行比较时,由于其 toString
或 valueOf
方法。例如,考虑将字符串原语与使用 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/359494/