gpt4 book ai didi

javascript - 类型未定义。哪个更快更好?

转载 作者:行者123 更新时间:2023-12-02 17:54:56 25 4
gpt4 key购买 nike

这里

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com