最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - check if JS object exists - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked May 28, 2012 at 16:19 NaigelNaigel 9,64417 gold badges71 silver badges109 bronze badges 2
  • typeof window["string"] === "object" – noob Commented May 28, 2012 at 16:25
  • 1 I would add a && window["string"] !== null to that to circumvent the typeof null being object – Alex K. Commented May 28, 2012 at 16:26
Add a ment  | 

5 Answers 5

Reset to default 7

If the object is in the global scope;

var exists = (typeof window["test"] !== "undefined");

If you're in a browser (i.e. not 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 very hard 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.

if( window[input])...

All global variables are properties of the window object. [] notation allows you to get them by an expression.

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.

if (typeof window['my_objname_str'] != 'undefined')
{
    // my_objname_str is defined
}

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 :

function doesItExist(oName){ 
   var e = (typeof window[oName] !== "undefined"); 
   return e;
}

is suitable for me.

发布评论

评论列表(0)

  1. 暂无评论