javascript 检查JS对象是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10787651/
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
check if JS object exists
提问by Naigel
I need to discover at runtime if an object with a given name exists, but this name is stored in a variable as a string.
我需要在运行时发现具有给定名称的对象是否存在,但该名称作为字符串存储在变量中。
For example, in my Javascript I have an object named test, then at runtime I write the word "text" in a box, and I store this string in a variable, let's name it input. How can I check if a variable named with the string stored in input variable exist?
例如,在我的 Javascript 中,我有一个名为 test 的对象,然后在运行时我将单词“text”写入一个框中,并将此字符串存储在一个变量中,让我们将其命名为 input。如何检查以输入变量中存储的字符串命名的变量是否存在?
回答by Alex K.
If the object is in the global scope;
如果对象在全局范围内;
var exists = (typeof window["test"] !== "undefined");
var exists = (typeof window["test"] !== "undefined");
回答by Amadan
If you're in a browser (i.e. not Node):
如果您使用浏览器(即不是 Node):
var varName = 'myVar';
if (typeof(window[varName]) == 'undefined') {
console.log("Variable " + varName + " not defined");
} else {
console.log("Variable " + varName + " defined");
}
However, let me say that I would find it veryhard to justify writing this code in a project. You should know what variables you have, unless you expect people to write plugins to your code or something.
然而,让我说,我会觉得很很难证明在一个项目中编写这些代码。您应该知道您拥有哪些变量,除非您希望人们为您的代码编写插件或其他内容。
回答by Niet the Dark Absol
if( window[input])...
All global variables are properties of the window
object. []
notation allows you to get them by an expression.
所有全局变量都是window
对象的属性。[]
符号允许您通过表达式获取它们。
回答by Zach
If you want to see whether it exists as a global variable, you can check for a member variable on the window object. window is the global object, so its members are globals.
如果要查看它是否作为全局变量存在,可以在window 对象上检查成员变量。window 是全局对象,所以它的成员是全局对象。
if (typeof window['my_objname_str'] != 'undefined')
{
// my_objname_str is defined
}
回答by quevedo
I'm writing my code but not allways can know if a method exists. I load my js files depending on requests. Also I have methods to bind objects "via" ajax responses and need to know, if they must call the default callbacks or werther or not particular a method is available. So a test like :
我正在编写我的代码,但并非总能知道方法是否存在。我根据请求加载我的 js 文件。此外,我有“通过”ajax 响应绑定对象的方法,并且需要知道,如果它们必须调用默认回调或不特定的方法可用。所以像这样的测试:
function doesItExist(oName){
var e = (typeof window[oName] !== "undefined");
return e;
}
is suitable for me.
适合我。