Check if JS object exists

I need to detect at runtime if an object with the given name exists, but that name is stored in the variable as a string.

For example, in my Javascript I have an object called test, then at runtime I write the word β€œtext” in a field and I store this string in a variable, let it call its input. How to check if a variable exists with the name stored in the input variable?

+4
source share
5 answers

If the object is in a global scope;

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

+6
source

If you are 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 it is very difficult for me to justify writing this code in a project. You need to know what variables you have if you do not expect people to write plugins in your code or something like that.

+1
source
 if( window[input])... 

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

+1
source

If you want to see if it exists as a global variable, you can check the member variable in the window object. window is a global object, so its members are global.

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

I write my code, but I don’t always know if a method exists. I upload js files depending on the requests. I also have methods for binding objects "through" ajax responses and you need to know if they should call the default callbacks or werther or the method is inaccurate. So a test like:

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

Works for me.

0
source

Source: https://habr.com/ru/post/1414743/


All Articles