I suggest you create an array to store all your a
elements like so:
var arr = [10, 15, 20];
Which you can then loop over using a for loop. In the array the 0th index represents the a1
and the n-1th index represents an
:
var arr = [10, 15, 20];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Another approach would be to use an object, where a1
, a2
, ... an
are keys in your object:
var obj = {
'a1': 10,
'a2': 15,
'a3': 20
}
You can then use bracket notation to access your keys and values:
var obj = {
'a1': 10,
'a2': 15,
'a3': 20
}
for (var i = 1; i <= 3; i++) {
console.log(obj['a' + i]);
}
...or use a for...in
loop to loop over your properties instead:
var obj = {
'a1': 10,
'a2': 15,
'a3': 20
}
for (var prop in obj) {
console.log(obj[prop]);
}