5

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.

Graham
  • 7,807
  • 20
  • 69
  • 114

4 Answers4

7

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]

Alnitak
  • 334,560
  • 70
  • 407
  • 495
6

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;
});
Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
1

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);
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
0

Use:

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

Hope This will help you

asif
  • 11
  • 4