微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在三元运算符中检查未定义的变量?

我有三元操作的问题:

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是否未定义以及在未定义时分配空白对象{}的最佳和简短方法是什么?

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

PS:我目前正在使用(typeof abc!==“undefined”)代替[[检查abc的最佳方式]]

解决方法:

while b and c throw ReferenceError when abc is undefined

所以abc不仅仅是未定义的,它是未声明的.那里有很大的不同.

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

typeof abc === "undefined"

如果abc是未声明的标识符,那将是真的,没有错误.如果声明了abc并且包含未定义的值,那么也是如此.

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,并将其赋值为{}.如果它已声明,如果它是假的,我们用{}替换它的值.但是,如果它可能或不可能用let或const声明,那么上面也会抛出错误.

因此,要处理可能或不使用let或const声明的情况,我们需要完全不同的变量:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐