在 JavaScript 中 != 与 !== 相同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1946063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:00:54  来源:igfitidea点击:

In JavaScript is != same as !==

javascriptsyntax

回答by Amadiere

They are subtly not the same.

它们微妙地不同。

!=checks the value
!==checks the value and type

!=检查值
!==检查值和类型

'1' != 1   // false (these two are the same)
'1' !== 1 // true (these two are **not** the same).

In the previous example. The first half of the expression is a string, the second half is an integer.

在前面的例子中。表达式的前半部分是一个字符串,后半部分是一个整数。

回答by martinr

From

http://en.wikipedia.org/wiki/JavaScript_syntax#Operators

http://en.wikipedia.org/wiki/JavaScript_syntax#Operators

!== Not identical

!== 不相同

!= Not equal

!= 不相等

AND "Identical means equal and of same type."

AND “相同意味着相同且类型相同。”

From

http://docstore.mik.ua/orelly/webprog/jscript/ch05_04.htm

http://docstore.mik.ua/orelly/webprog/jscript/ch05_04.htm

"In JavaScript, numbers, strings, and boolean values are compared by value. ... On the other hand, objects, arrays, and functions are compared by reference. "

“在 JavaScript 中,数字、字符串和布尔值是按值比较的。……另一方面,对象、数组和函数是按引用比较的。”

--

——

So in summary are they the same? No, because there is an additional test with !== (over !=) for type sameness as well as equalness.

所以总而言之,它们是一样的吗?不,因为有一个额外的 !== 测试(超过 !=)用于类型相同性和相等性。

回答by Fortega

No, it is not the same. See for example here.

不,它不一样。参见此处的示例。

4 !== '4' returns true   (and 4 === '4' returns false)
4 != '4'  returns false  (and 4 == '4'  returns true)

回答by Sean Devlin

The big difference is that != performs type coercion. That is, one value is effectively cast to the other before equality is checked. This is why, as in Amadiere's answer:

最大的区别在于 != 执行类型强制。也就是说,在检查相等性之前,一个值被有效地转换为另一个值。这就是为什么,正如 Amadiere 的回答:

'1' != 1

evaluates to false. The same holds true for == v. ===. In general, avoid == and != unless you specifically want coercion to be performed. Use === and !== and check for exactly the result you're looking for.

评估为假。== v. === 也是如此。通常,除非您特别希望执行强制转换,否则应避免使用 == 和 !=。使用 === 和 !== 并检查您正在寻找的确切结果。

回答by Sarfraz

Checks not only value but also the type of the things compared. This is also same in php and some other languages too.

不仅检查价值,还检查所比较事物的类型。这在 php 和其他一些语言中也是一样的。