0

I'm learng some code with Javascript. I would like to console.log Increment Variable such as a1,a2,a3,a4 and so on. How can I implement it?

My only solution is eval() in a for loop:

console.log(eval('a'+i)).

However, it's not recommended in javascript.

var a1=10,a2=15,a3=20;
for(var i=1;i<=3;i++){
  console.log(eval('a'+i));
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
BoBo
  • 25
  • 3
  • if this is in the global scope ... `console.log(this['a'+i])` – Jaromanda X Jun 19 '19 at 03:57
  • 1
    If those were globals you can do `window['a'+i]`. That's just a curiosity, you should not make them globals. – Gerardo Furtado Jun 19 '19 at 03:57
  • 3
    Store the values in an array? Then you can do `a[1], a[2], a[i]...` – Herohtar Jun 19 '19 at 03:57
  • 1
    @Herohtar is correct - what you're looking for is an array. – eddiewould Jun 19 '19 at 03:59
  • 4
    Possible duplicate of [Increment the name of variable](https://stackoverflow.com/questions/7730761/increment-the-name-of-variable) and [How do I create dynamic variable names inside a loop?](https://stackoverflow.com/questions/8260156) – adiga Jun 19 '19 at 04:01
  • BoBo, Welcome to JavaScript. If you have a requirement like this then you should create an array of objects like var a = [{a: 10},{a: 15},{a: 30}]; a.map((item) => console.log(item.a)). This is also a use case may vary on requirements. – Shashank Malviya Jun 19 '19 at 04:07
  • 1
    @BoBo Please do not edit your question for an unrelated one, specially after receiving answers. I rolled your edit back. – Gerardo Furtado Jun 19 '19 at 04:10

2 Answers2

1

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]);
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0
var a = [10, 15, 20];
for (var i=0; i<a.length; i++){
    console.log("The value of a[i] is", a[i]);
}
eddiewould
  • 1,555
  • 16
  • 36
  • If you're working with modern JavaScript, you could look into a `for of` loop, declaring the variable reference `a` as `const` etc – eddiewould Jun 19 '19 at 04:02
  • Thanks ,Sir.However,the key is i don't know the value of variable stored in Array. – BoBo Jun 19 '19 at 04:08