Find a variable using jquery

There are several javascript variables on my page:

var opts_???? = ... var opts_???? = ... var opts_???? = ... 

???? a random number is assigned to the content management system, so I don’t know the full name of the variable.

I am looking for any undefined.

Is there a way in jQuery to scroll through all variables starting with opts_ so that I can check them for undefined?

All variables are global if that helps.

If not in jQuery, I will settle for plain javascript.

+5
source share
4 answers

This is only possible if all variables have been declared in the global scope (and therefore are also available as properties of the global window object).

From your name, you can use Object.keys(window) to get the names of all such properties, and then use either $.each or Array.prototype.forEach to check each of them in turn.

 var opts = Object.keys(window).filter(function(n) { return n.substring(0, 5) === 'opts_'; }); var opts_undefined = opts.filter(function(n) { return window[n] === undefined; }); 

[written as two calls for clarity on effectiveness]

+7
source

If the variables are in the global scope (that is, they are not created inside the function), they should also be available as properties of the window object. In other words, the opts_1234 variable can also be obtained as window.opts_1234 or window['opts_1234'] .

The easiest way to capture all variables:

 var variables = Object.keys(window).filter(function(prop) { return prop.substring(0, 5) === 'opts_'; }); 

variables now contains an array of names, for example ['opts_1', 'opts_666']

You can also expand this filter to include only those variables that are not undefined:

 var variables = Object.keys(window).filter(function(prop) { return prop.substring(0, 5) === 'opts_' && window[prop] !== undefined; }); 
+6
source

 var opts_1 = 'test'; var opts_2 = 'test1'; var opts_3 = 'test2'; var opts_4 = undefined; var vars = Object.keys(window).filter(function(key){ return (key.indexOf("opts_")!=-1 && window[key] == undefined) }); console.log(vars); 
+1
source

Using:

 var marker='opts_'; var results=$('selector').find(marker); 

Hope this helps you

0
source

All Articles