Javascript 如果我不知道变量是否存在,如何将变量与未定义进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2778901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare variables to undefined, if I don’t know whether they exist?
提问by ncubica
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?
在 JavaScript 中,您可以声明一个变量,如果是undefined,您可以检查variable == undefined;我知道,但是如果它在内存中,你怎么能比较一个你还不知道的值呢?
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?
有没有不使用try- 的方法catch?
回答by Makram Saleh
The best way is to check the type, because undefined/null/falseare a tricky thing in JS.
So:
最好的办法是检查类型,因为undefined/ null/false在JS一件棘手的事情。所以:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeofalways returns a string, and doesn't generate an error if the variable doesn't exist at all.
请注意,typeof始终返回一个字符串,如果该变量根本不存在,则不会生成错误。
回答by Timmy
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
如果你正在做大量的 javascript 编程,当你想要进行类型特定的检查时,你应该养成使用 === 和 !== 的习惯。
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.comit might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
此外,如果您打算使用大量的 javascript,我建议通过 JSLint http://www.jslint.com运行代码,起初它可能看起来有点严厉,但 JSLint 警告您的大部分事情最终都会出现回来咬你。
回答by Delan Azabani
if (document.getElementById('theElement')) // do whatever after this
For undefined things that throw errors, test the property name of the parent object instead of just the variable name - so instead of:
对于抛出错误的未定义事物,测试父对象的属性名称而不仅仅是变量名称 - 所以而不是:
if (blah) ...
do:
做:
if (window.blah) ...
回答by Mr.Hunt
!undefinedis true in javascript, so if you want to know whether your variable or object is undefined and want to take actions, you could do something like this:
!undefined在 javascript 中是 true,所以如果你想知道你的变量或对象是否未定义并想要采取行动,你可以做这样的事情:
if(<object or variable>) {
//take actions if object is not undefined
} else {
//take actions if object is undefined
}
回答by Thevs
if (!obj) {
// object (not class!) doesn't exist yet
}
else ...

