Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a variable using jquery [duplicate]

I have a number of javascript variables on my page:

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

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

I'm looking for any undefined ones.

Is there a way in jQuery to loop through all variables that start with opts_ so that I can test them for being undefined?

The variables are all global, if that helps.

If not in jQuery, I'll settle for regular javascript.

like image 534
Graham Avatar asked Jun 07 '16 14:06

Graham


2 Answers

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

Since yours are, you can use Object.keys(window) to obtain the names of all such properties, and then use either $.each or Array.prototype.forEach to test 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 over efficiency]

like image 88
Alnitak Avatar answered Sep 18 '22 12:09

Alnitak


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

The easiest way to grab all the variables would be:

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

Now variables contains an array of names, like ['opts_1', 'opts_666']

You can also extend that filter to only include those variables that aren't undefined:

var variables = Object.keys(window).filter(function(prop) {
    return prop.substring(0, 5) === 'opts_' && window[prop] !== undefined;
});
like image 36
Stephan Muller Avatar answered Sep 17 '22 12:09

Stephan Muller