gpt4 book ai didi

javascript - 如何检查三元运算符中的 undefined variable ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:53:46 31 4
gpt4 key购买 nike

我对三元运算有疑问:

let a = undefined ? "Defined!" : "Definitely Undefined",
b = abc ? "Defined!" : "Definitely Undefined", // ReferenceError
c = (abc !== undefined) ? "Defined!" : "Definitely Undefined", // ReferenceError
d = (typeof abc !== "undefined") ? "Defined!" : "Definitely Undefined"

// results: a = d = "Definitely Undefined",
// while b and c throw ReferenceError when abc is undefined

在访问其属性以及分配空白对象 之前检查 abc 是否 undefined最佳和最短方法是什么{} 如果未定义

let a = [[best way to check abc]] ? {[abc.label1]: 2, [abc.label2]: 1} : {}

PS:我目前正在使用 (typeof abc !== "undefined") 代替 [[best way to check abc]]

最佳答案

while b and c throw ReferenceError when abc is undefined

所以 abc 不仅是未定义的,而且是未声明的。那里有很大的不同。

如果您需要处理未声明的 abc,唯一安全的方法(没有 try/catch)是使用 类型:

typeof abc === "undefined"

如果 abc 是一个未声明的标识符,那将是正确的,没有错误。如果声明了 abc 并且包含值 undefined,它也将为真。

What is the best and short way to check if abc is undefined before accessing its properties as well as assign blank object {} if undefined?

可能使用 var 来确保它被声明:

var abc = abc || {};

重复的 var 声明不是错误(重复的 let 声明是)。因此,对于上面的内容,如果 abc 未声明,它会被声明为初始值 undefined 并且我们将其分配给 {}。如果已声明,如果它是假的,我们将其值替换为 {}但是,如果它可以用也可以不用letconst 声明,那么上面的代码也会抛出错误。

因此,为了处理可能使用或不使用 letconst 声明的情况,我们需要一个完全不同的变量:

let ourabc = typeof abc === "undefined" || !abc ? {} : abc;

如果 abc 未声明或包含虚假值,则将 ourabc 设置为 {}。由于所有非 null 对象引用都是真实的,并且您已经说过要访问对象属性,所以这可能是最短的方法。

关于javascript - 如何检查三元运算符中的 undefined variable ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48659442/

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