问题描述
我正在使用 JSLint 来检查 JavaScript,它返回了许多替换 ==(两个等号)和===
(三个等号),当在里面比较idSele_UNVEHtype.value.length == 0
if
语句.
Is there a performance benefit to replacing ==
with ===
?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==
?
推荐答案
严格相等运算符 (===
) 与抽象相等运算符 (==
) 的行为相同) 除了没有进行类型转换,并且类型必须相同才能被视为相等.
==
运算符将在进行任何必要的类型转换后比较是否相等.===
运算符将不进行转换,因此如果两个值的类型不同,===
将简单地返回 错误
.两者都一样快.
The ==
operator will compare for equality after doing any necessary type conversions. The ===
operator will not do the conversion, so if two values are not the same type ===
will simply return false
. Both are equally quick.
引用 Douglas Crockford 出色的 JavaScript:好的部分,
To quote Douglas Crockford's excellent JavaScript: The Good Parts,
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
'
' == 0 // true
缺乏传递性令人担忧.我的建议是永远不要使用邪恶的双胞胎.相反,始终使用 ===
和 !==
.刚刚显示的所有比较都使用 ===
运算符产生 false
.
更新:
@Casebash 在评论和 @Phillipe Laybaert 的 回答关于对象.对于对象,==
和 ===
的作用是一致的(特殊情况除外).
Update:
A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert's answer concerning objects. For objects, ==
and ===
act consistently with one another (except in a special case).
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
构造函数创建的字符串对象进行比较.
The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString
or valueOf
method. For example, consider the comparison of a string primitive with a string object created using the String
constructor.
"abc" == new String("abc") // true
"abc" === new String("abc") // false
这里的 ==
运算符正在检查两个对象的值并返回 true
,但是 ====
看到它们'不是同一类型并返回 false
.哪一个是正确的?这实际上取决于您要比较的内容.我的建议是完全绕过这个问题,只是不要使用 String
构造函数从字符串文字创建字符串对象.
Here the ==
operator is checking the values of the two objects and returning true
, but the ===
is seeing that they're not the same type and returning false
. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String
constructor to create string objects from string literals.
参考
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
这篇关于在 JavaScript 比较中应该使用哪个等于运算符 (== vs ===)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!