If you're going to need to iterate through a set of variables, plan ahead and put them inside an object:
var myArrays = {
array1: [],
array2: [1, 2],
array3: [4, 4],
"any-name-you-want-works": []
};
Accessing them is still straightforward:
myArrays.array1.push(1);
myArrays["any-name-you-want-works"].push(1);
Adding a new array to myArrays
:
myArrays.array4 = [3, 5];
And iterating is made easy (this is the recommended way):
for (var arr in myArrays) {
if (object.hasOwnProperty(arr)) {
arr.push(1);
}
}
If you don't need to support old browsers, you can use newer features as well (source):
Object.keys(myArrays).forEach(function(key, index) {
myArrays[key].push(1);
});
More info on Object.keys()
.
Then, if you're using a popular lib like underscore or lodash, you can do lots of thing easily on objects and arrays:
_.chain(myArrays)
.each(function(arr) { arr.push(1) }) // adds one to each array
.first() // takes the first array
.map(function(val) { return val *2; }) // and multiply each value
.reverse() // then reverse those values
.value(); // and get the array
As I mentioned in a comment, you shouldn't pollute the global window object and also iterate through it to avoid collision or unexpected behaviors.
Wrapping your code inside an IIFE (Immediatly-Invoked Function Expression) is always a good idea, instead of using the global scope, for multiple reasons, but that's a whole other discussion and we can achieve what you want without it (for this question anyway).