[英]When checking for undefined'ness in Javascript, should I use != or !==?
When I want to make sure a variable x
is defined, before using it, I use:当我想确保定义了一个变量
x
,在使用它之前,我使用:
if (typeof x !== "undefined") {
// do stuff with x
}
but I've noticed that others, eg in this question , use !==
instead of !=
for the comparison.但我注意到其他人,例如在这个问题中,使用
!==
而不是!=
进行比较。 Which one should I be using, and why?我应该使用哪一种,为什么?
Note: I realize I can be using !==
.注意:我意识到我可以使用
!==
。 The question is whether I should (and whether there will be any difference in behavior).问题是我是否应该(以及行为上是否会有任何差异)。
As noted in a comment by VLAZ, the typeof
operator is guaranteed to return a string.正如 VLAZ 在评论中所指出的,
typeof
运算符保证返回一个字符串。 If you compare the result to another string, then ==
and ===
(or !=
and !==
) will do the exact same thing.如果将结果与另一个字符串进行比较,则
==
和===
(或!=
和!==
)将执行完全相同的操作。
actually, the best approach would be to check if a value is falsy
, and based on MDN this is the list of falsy values:实际上,最好的方法是检查一个值是否为
falsy
值,根据 MDN,这是假值列表:
This is an empty string (the length of the string is zero).这是一个空字符串(字符串的长度为零)。 Strings in JavaScript can be defined with double quotes "", single quotes '', or Template literals ``.
JavaScript 中的字符串可以用双引号 ""、单引号 '' 或模板文字 `` 定义。
null null - the absence of any value null null - 没有任何值
so based on your code what you can do is simply:因此,根据您的代码,您可以做的很简单:
if (!x) { // check for all the falsy values.
// do stuff with x
}
in the other hand, you ask for the difference of !=
and !==
, well basically taking some examples you can see the difference:另一方面,你要求
!=
和!==
的区别,基本上举一些例子你可以看到区别:
0 == false // true, because false is equivalent of 0
0 === false // false, because both operands are of different type
2 == "2" // true, auto type coercion, string converted into number
2 === "2" // false, since both operands are not of same type
as mentioned by @VLAZ comment, these cases will only work if the variable x
is defined, otherwise you will have the following error:正如@VLAZ 评论所提到的,这些情况只有在定义了变量
x
时才有效,否则会出现以下错误:
"Uncaught ReferenceError: x is not defined"
“未捕获的 ReferenceError:x 未定义”
so on your case you could only use !=
because you will compare string
vs string
and you will avoid having to check if the variable was or not created.因此,在您的情况下,您只能使用
!=
因为您将比较string
与string
并且不必检查变量是否已创建。
if (typeof x != "undefined") {
// do stuff with x
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.