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

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

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

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


当前回答

=== 检查相同的侧面在类型和值均等。


例子:

'1' === 1 // will return "false" because `string` is not a `number`

常见的例子:

0 == ''  // will be "true", but it's very common to want this check to be "false"

另一个常见的例子:

null == undefined // returns "true", but in most cases a distinction is necessary

很多时候,一个不类型的检查会很有用,因为你不在乎值是否不定义,零,0或“。

其他回答

这里是一个方便的比较表,显示发生的转换和 ==和 ===之间的差异。

如结论所说:

“使用三种平等,除非你完全理解两种平等发生的转变。

http://dorey.github.io/JavaScript - 平等 - 表/

在这里的答案中,我没有读到什么是平等的意思,有些人会说 === 意味着平等和相同的类型,但这不是真的。

所以,让我们采取下列代码:

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

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

在这里相同:

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

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

var a = { };
var b = { };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

这种行为并不总是显而易见的,有更多的故事,而不是平等和同类。

规则是:

对于值类型(数字): a === b 如果 a 和 b 具有相同的值,并且具有相同的类型,则返回真实。


下一篇:特殊案例...

var a = "12" + "3";
var b = "123";

alert(a === b); // returns true, because strings behave like value types

但是,这个问题怎么样呢?

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

我以为线条像值类型一样行事吗? 好吧,这取决于你问谁...... 在这种情况下, a 和 b 不是相同的类型. a 是类型对象,而 b 是类型线条。

在您的使用中,不可能有两项操作之间的性能差异. 没有类型转换要进行,因为两项参数已经是相同的类型. 两项操作将有一个类型比较,其次是值比较。

我在Firefox使用Firebug测试了此类代码:

console.time(“testEquality”); var n = 0; while (true) { n++; if (n == 100000) break; } console.timeEnd(“testEquality”);

console.time(“testTypeEquality”); var n = 0; while (true) { n++; if (n === 100000) break; } console.timeEnd(“testTypeEquality”);

我的结果(每次测试5次,平均):

==: 115.2
===: 114.4

所以我会说小差异(这是超过100000 iterations,记住)是不可忽视的。 性能不是一个理由做 ===. 类型安全(好,安全,你会得到在JavaScript),和代码质量是。

=== 检查相同的侧面在类型和值均等。


例子:

'1' === 1 // will return "false" because `string` is not a `number`

常见的例子:

0 == ''  // will be "true", but it's very common to want this check to be "false"

另一个常见的例子:

null == undefined // returns "true", but in most cases a distinction is necessary

很多时候,一个不类型的检查会很有用,因为你不在乎值是否不定义,零,0或“。