问题描述
最近,当我想出这个错误时,我通过JSLint运行了一些代码。我认为这个错误很有趣但它自动假设所有==应该是===。
Recently I was running some of my code through JSLint when I came up with this error. The thing I think is funny about this error though is that it automatically assumes that all == should be ===.
这真的有意义吗?我可以看到很多你不想比较类型的实例,我担心这实际上会导致问题。
Does that really make any sense? I could see a lot of instances that you would not want to compare type, and I am worried that this could actually cause problems.
预期一词意味着这应该是每次都做的.....这对我来说没有意义。
The word "Expected" would imply that this should be done EVERY time.....That is what does not make sense to me.
推荐答案
IMO,盲目地使用 ===
,无需了解 类型转换的工作原理没有多大意义。
IMO, blindly using ===
, without trying to understand how type conversion works doesn't make much sense.
关于Equals运算符 ==
的主要恐惧是比较规则取决于比较的类型可以使运算符不可传递,例如,如果:
The primary fear about the Equals operator ==
is that the comparison rules depending on the types compared can make the operator non-transitive, for example, if:
A == B AND
B == C
并不能真正保证:
A == C
例如:
'0' == 0; // true
0 == ''; // true
'0' == ''; // false
Strict Equals运算符 === $ c $当您比较相同类型的值时,c>不是必需的,最常见的例子:
The Strict Equals operator ===
is not really necessary when you compare values of the same type, the most common example:
if (typeof foo == "function") {
//..
}
我们比较 typeof
运算符的结果,总是 字符串,带有字符串字面值...
We compare the result of the typeof
operator, which is always a string, with a string literal...
或者当您知道类型强制规则时,例如,检查某些内容是否为 null
或 undefined
某事:
Or when you know the type coercion rules, for example, check if something is null
or undefined
something:
if (foo == null) {
// foo is null or undefined
}
// Vs. the following non-sense version:
if (foo === null || typeof foo === "undefined") {
// foo is null or undefined
}
这篇关于JSLint预期'==='而是看到'=='的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!