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.

2
  • It is not possible in this way. But have a look at this discussion maybe it fits in your context Commented Apr 16, 2016 at 5:30
  • 1
    the simple way is to make a array instead of a1,a2... Commented Apr 16, 2016 at 5:31

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But wait! Douglas Crockford says eval is evil! /s :D
1
var a1 = 100, a2 = 400, a3 = 700, a4 = 800;
var arr= [];
arr.push(a1,a2,a3,a4);
alert(arr);

2 Comments

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.
u have specified 4 vars thats why I provided this solution
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);

3 Comments

whats the common difference btn map and eval. what should use in my app.
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 stackoverflow.com/questions/197769/… . Use the map, its a valuable data structure.
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
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>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.