问题

我使用 JSLint 浏览JavaScript,并返回了许多建议以替换 == < / code>里面的 idSele_UNVEHtype.value.length == 0 时,用 === (三个等号) if 语句.

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

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

如果没有发生类型转换,那么 == 会有性能提升吗?



解决方法

身份( === )运算符与等式( == )运算符的行为相同,除非不进行类型转换,类型必须相同被视为平等.

参考: JavaScript教程:比较运算符

== 运算符会在进行任何必要的类型转换后比较等于. === 运算符不会进行转换,因此如果两个值不是相同类型 === false .两者同样快.

如需引用Douglas Crockford的优秀 JavaScript:好零件,

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

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.


Update:

@Casebash 在评论和@Phillipe Laybaert的 回答有关参考类型.对于引用类型 == === 彼此一致(除了特殊情况).

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




相关问题推荐