0

How to push variable a1, a2, a3, a4 values inside for loop array.

var a1 = 100, a2 = 400, a3 = 700, a4 = 800;
var arr= [];
for (var i = 1; i <= 4; i++) {
    arr.push("a"+i);
}
alert(arr);

The result is a1,a2,a3,a4 instead of 100,400,700,800.

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Rakesh
  • 329
  • 1
  • 4
  • 14

4 Answers4

5

Use Eval for the solution of the problem.

 var a1 = 100, a2 = 400, a3 = 700, a4 = 800;
        var arr= [];
        for (var i = 1; i <= 4; i++) {
            arr.push(eval("a"+i));
        }
        alert(arr);

Hope this helps you.

Nitin Garg
  • 888
  • 6
  • 7
1
var a1 = 100, a2 = 400, a3 = 700, a4 = 800;
var arr= [];
arr.push(a1,a2,a3,a4);
alert(arr);
dhruv jadia
  • 1,684
  • 2
  • 15
  • 28
  • your solution is fine for less numbers of variables. but i have more than 100 variable set, so not possible to push statically variables in array. – Rakesh Apr 16 '16 at 05:46
  • u have specified 4 vars thats why I provided this solution – dhruv jadia Apr 16 '16 at 05:48
1

You can do without eval by using a map store your variables.

var map = { a1: 100, a2: 400, a3: 700, a4: 800 };
var arr = [];

for (var i = 1; i <= 4; i++) {
    arr.push(map["a" + i]);
}
console.log(arr);
Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109
  • whats the common difference btn **map** and **eval**. what should use in my app. – Rakesh Apr 16 '16 at 05:49
  • `eval` should be avoided at all cost, most people will never consider using `eval`. It has bad performance and, while not in your case, is usually a security risk. Read more here http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil . Use the `map`, its a valuable data structure. – Daniel Kobe Apr 16 '16 at 06:13
  • A map simply "maps" a key to a value. In this case a key would be `a1` and the value `100`. Now I can ask the map for a key and it will return a value. You can also access `a1`'s value like so `map.a1` – Daniel Kobe Apr 16 '16 at 06:20
1

You could use the window object for accessing global variables.

var a1 = 100,
    a2 = 400,
    a3 = 700,
    a4 = 800;
    arr = [];

for (var i = 1; i <= 4; i++) {
    arr.push(window['a' + i]);
}

document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392