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.
The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.
Naming Conventions for JavaScript VariablesA variable name must start with a letter, underscore ( _ ), or dollar sign ( $ ). A variable name cannot start with a number. A variable name can only contain alpha-numeric characters ( A-z , 0-9 ) and underscores. A variable name cannot contain spaces.
The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well.
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]);
}
}
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