【发布时间】:2018-07-17 11:39:22
【问题描述】:
我对三元运算有疑问:
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 以及在 undefined 时分配空白对象 {} 的最佳和短方法是什么?
let a = [[best way to check abc]] ? {[abc.label1]: 2, [abc.label2]: 1} : {}
PS:我目前使用(typeof abc !== "undefined") 代替[[best way to check abc]]
【问题讨论】:
-
为什么有一个未声明的变量?还是只需要检查
undefined? -
没错,就我而言,我希望有人可以为我提供该变量:D
-
确切地说,我正在开发一个通用代码,可以说 abc 可能已定义也可能未定义
-
@KiranShakya 在这种情况下,您的代码
typeof abc !== "undefined"也失败了,对吧?因为abc没有定义? -
不!为了澄清一点,我使用该部分作为三元运算的条件,如您在第 4 行中看到的那样
标签: javascript typescript ecmascript-6