Get all JS variables starting with a specific string

I am writing a plugin for a website for which I have no control, besides my ability to add JS code to it (in fact, this is a set of html documents created by the outdated wysiwyg html editor).

For my purposes, I need to get all the variables that are named in a certain way. A name always starts with zzzand ends with a number, from zzz1to zzz999999. Now I am 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 besides iterating through a million uncertain ones.

+5
source share
2 answers

( window), , . , .

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

:)

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

}

:)... ...

+1

All Articles