8

I'm writing a plugin for a website that I have no control over except my ability to add JS code to it (in fact it's a set of html docs generated by an obsolete wysiwyg html editor).

For my purposes, I need to get all variables that are named in a certain way. The name always begins with zzz and ends with a number, from zzz1 to zzz999999. Right now I'm doing the following:

for (var i=1; i<999999; i++) {
    if (typeof window['zzz'+i] !== 'undefined') { 
       ArrayOfAllFoundVariables.push( window['zzz'+i] )
    }
}

I wonder if there is a more efficient way to detect these variables other than iterating through a million of undefineds.

2 Answers 2

12

You can iterate through all top level variables (properties of window), and then test if their name match some regex pattern. Collect the matching variables as before.

var pattern = /^zzz[0-9]+/;
for (var varName in window) {
    if (pattern.test(varName)) {
        ArrayOfAllFoundVariables.push(window[varName]);
    }
}
1

Mikke beat me to it :)

for (element in window) {
  if (element.substring(0,3) == 'zzz') {
    ArrayOfAllFoundVariables.push(window[element]);
  }

}

but I missed out the number part :) ... well done Mikke ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.