如果我不知道它们是否存在,如何将变量与undefined进行比较? [英] How to compare variables to undefined, if I don’t know whether they exist?
问题描述
在JavaScript中,您可以声明一个变量,如果它是 undefined
,您可以检查 variable == undefined
;我知道,但你如何比较一个你不知道的值,如果它在内存中?
In JavaScript you can declare a variable and if it’s undefined
, you can check variable == undefined
; I know that, but how can you compare a value that you don’t know yet if it’s in memory?
例如,我有一个类是在用户单击一个按钮。在此之前,该类是未定义的 - 它在任何地方都不存在;我怎么比较呢?
For example, I have a class which is created when the user clicks a button. Before this, the class is undefined — it doesn’t exist anywhere; how can I compare it?
有没有办法不用试试
- catch
?
Is there a way without using try
–catch
?
推荐答案
最好的方法是检查类型,因为 undefined
/ null
/ false
在JS中是一个棘手的事情。
所以:
The best way is to check the type, because undefined
/null
/false
are a tricky thing in JS.
So:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
请注意 typeof
总是返回一个字符串,如果该变量根本不存在则不会产生错误。
Note that typeof
always returns a string, and doesn't generate an error if the variable doesn't exist at all.
这篇关于如果我不知道它们是否存在,如何将变量与undefined进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!