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

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

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

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


当前回答

一个简单的例子是

2 == '2'  -> true, values are SAME because of type conversion.

2 === '2'  -> false, values are NOT SAME because of no type conversion.

其他回答

一个简单的例子是

2 == '2'  -> true, values are SAME because of type conversion.

2 === '2'  -> false, values are NOT SAME because of no type conversion.

它建议取代 ==与 ===的原因是 ===操作员比 ==更可靠。在我们的背景下可靠的手段 ===也去类型检查. 考虑到最好的编程做法,我们应该总是选择更可靠的功能比不可靠的一个。 再一次,每当我们想到的正是相同的操作员大部分时间,我们是默认考虑类型应该是相同的。

是的,平等 ==和身份 ===操作员之间有一个很大的差异. 通常,身份操作员表现更快,因为没有类型的转换完成. 但如果值是相同的类型,你会看到没有差异. 查看我的帖子 JavaScript 平等操作员的传说,解释了细节,包括类型的转换和比较算法,有很多例子。

首先,一些关于JavaScript行方程式的术语:双方程式正式称为抽象平等比较运营商,而三方程式则称为严格平等比较运营商。

console.log(3 == "3"); // true
console.log(3 === "3"); // false.
console.log(3 == "3"); // true
console.log(3 === "3"); // false.

使用兩個平等的標誌返回真實,因為字符串“3”在比較之前轉換為3號。

console.log(true == '1'); // true
console.log(true === '1'); // false
console.log(true == '1'); // true
console.log(true === '1'); // false

再一次,抽象的平等比较进行类型转换,在这种情况下,两者都是真实的和“1”字符串转换为1号,结果是真实的。

如果你明白你正好在你的道路上区分 ==和 ===. 但是,有一些场景,其中这些运营商的行为是不直觉的。

console.log(undefined == null); // true
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.
console.log(undefined == null); // true     
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.

console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false
console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false

下面的例子是有趣的,因为它描述了字符串与字符串对象不同。

console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false
console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false

让我们添加这个建议:

如果有疑问,请阅读规格!

請讓我解釋如何閱讀規格來澄清這個問題. 我看到,在這個非常古老的主題中,沒有人對非常奇怪的效果有答案. 所以,如果你能閱讀一個規格,這將非常幫助你在你的職業。

搜索 PDF 文件为 === 引导我到规格的第 56 页: 11.9.4. The Strict Equals Operator ( === ),然后通过规格我发现:

我发现新的线条(“a”)是一个对象,并使用步骤1:返回错误,如果类型不同。


Aidiakapi在下面的评论中写道:

从规格 11.2.2 新操作员:如果类型(构建器)不是对象,扔一个 TypeError 例外. 换句话说,如果 String 不是对象类型,它不能与新操作员一起使用。

而这最终意味着:新线(“a”)!==“a”。