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.
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]
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With