如何在三元运算符中检查未定义的变量? [英] How to check undefined variable in a ternary operator?
问题描述
三元运算存在问题:
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属性并分配空白对象之前,检查abc是否为
是否为 undefined
的 最佳和简短方法 是什么?{} 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
?
let a = [[best way to check abc]] ? {[abc.label1]: 2, [abc.label2]: 1} : {}
PS:我目前正在使用(typeof abc!=="undefined")
代替 [[检查abc的最佳方法]] 代码>
PS: I am currently using (typeof abc !== "undefined")
in place of [[best way to check abc]]
推荐答案
b和c时,当abc未定义时抛出ReferenceError
while b and c throw ReferenceError when abc is undefined
所以 abc
不仅是未定义的,它是未声明的.那里有很大的不同.
So abc
isn't just undefined, it's undeclared. There's a big difference there.
如果您需要处理未声明的 abc
,唯一安全的方法(无需 try
/ catch
)是使用 typeof
:
If you need to handle abc
being undeclared, the only safe way to do that (without try
/catch
) is with typeof
:
typeof abc === "undefined"
如果 abc
是未声明的标识符,那将是正确的,没有错误.如果声明了 abc
并包含值 undefined
.
That will be true, without error, if abc
is an undeclared identifier. It will also be true if abc
is declared and contains the value undefined
.
在访问其属性之前检查
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
来确保已声明:
Probably using var
to ensure it's declared:
var abc = abc || {};
重复的 var
声明不是错误(重复的 let
声明是).因此,使用上面的代码,如果未声明 abc
,则会使用初始值 undefined
对其进行声明,然后将其分配为 {}
.如果已声明,则在错误的情况下将其值替换为 {}
.但是,如果可能会或可能不会使用 let
或 const
进行声明,则上述内容也会引发错误.
Duplicate var
declarations are not errors (duplicate let
declarations are). So with the above, if abc
is undeclared, it gets declared with the initial value undefined
and we assign it {}
. If it's declared, we replace its value with {}
if it's falsy. But, if it may or may not be declared with let
or const
, then the above will throw an error as well.
因此,要处理可能会或可能不会使用 let
或 const
声明的情况,我们完全需要一个不同的变量:
So to handle the case where it may or may not be declared with let
or const
, we need a different variable entirely:
let ourabc = typeof abc === "undefined" || !abc ? {} : abc;
如果未声明 abc
或包含虚假值,则将 ourabc
设置为 {}
.由于所有非
That sets ourabc
to {}
if abc
is undeclared or if it contains a falsy value. Since all non-null
object references are truthy, and you've said you want to access object properties, that's probably the shortest way.
这篇关于如何在三元运算符中检查未定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!