Graham Graham - 10 months ago 26
jQuery Question

Find a variable using jquery

I have a number of javascript variables on my page:

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

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
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]