这个问题已经在这里有一个答案:
如何检查JavaScript中的“未定义”? [重复] 16答案在JavaScript中,您可以声明一个变量,如果undefined ,则可以检查variable == undefined ; 我知道,但是如果你在记忆中如何比较你还不知道的值呢?
例如,我有一个类,当用户点击一个按钮时创建。 在此之前,这个课程是未定义的 - 它不存在于任何地方; 我该怎么比较呢?
有没有使用try - catch ?
This question already has an answer here:
How to check for “undefined” in JavaScript? [duplicate] 16 answersIn 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?
Is there a way without using try–catch?
最满意答案
最好的方法是检查类型 ,因为undefined / null / false在JS中是一件棘手的事情。 所以:
if(typeof obj !== "undefined") { // obj is a valid variable, do something here. }请注意, typeof总是返回一个字符串,如果该变量根本不存在,则不会生成错误。
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. }Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.
更多推荐
发布评论