I’m just wondering if it’s possible to declare multiple variables using a for loop in Javascript.
Example: I have 4 <article> elements whose Ids are article1 article2 article3 and article4. Instead of declaring each variable independently, I’d like to do it in a loop (as they use essentially the same code and I don’t want to repeat myself!).
Something like:
window.ready = function(){
for (var i=1; i<=4; i++){
var article[i] = document.getElementById("article" + i);
}
}
The above returns an error with an unexpected [, so my syntax must be off (I’m very new to JS), but (a) is this on the right track and (b) will these be global variables if I run them in a window.ready function?
You cannot set a variable name with
[char. Using it, you will get an exception of javascript. You can use a List/Array to do this, try with Array class, something like:With Array class, you are not required to specify the lenght, but if you want, you can set it on the constructor.
Another approach is use the
pushmethod to add elements on the array, for sample: