这里
var a = {}
什么时候
if(typeof a.b == "undefined"){
console.log("undefined");
}
if (!a.b){
console.log("undefined");
}
两者都返回"undefined"
以及何时
if(typeof c.b == "undefined"){
console.log("undefined");
}
if (!c.b){
console.log("undefined");
}
两者都会引发错误c is not defined
看起来像 2 if-else
上面的语句的作用是一样的。那么哪种方式更好呢?
最佳答案
如果您正在寻找一种方法来检查成员是否存在,您应该使用 in
运算符
if ("b" in a) {
...
}
引发错误c is not Define
,因为c
未在程序中的任何位置定义。
typeof a.b
将返回的是 a.b
中存储的数据类型。如果b
确实存在并且它的值实际上是undefined
怎么办? typeof a.b
和 !a.b
都将计算为真值。因此,它们不应该用于成员存在检查。
请查看this answer了解为什么 in
应该成为成员存在的首选。
关于javascript - 类型未定义。哪个更快更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21036373/