Rakesh Rakesh - 7 months ago 10
Javascript Question

How to push variables value inside for loop array

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.

Answer

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.

Comments