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.
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.
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.
eval is evil! /s :Dvar a1 = 100, a2 = 400, a3 = 700, a4 = 800;
var arr= [];
arr.push(a1,a2,a3,a4);
alert(arr);
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);
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.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