Reputation: 1834
I have an array that I am adding objects to. I would like to control the number of objects that are added to the array using a number.
for (var i = 0; i < numberOfCountries; i++) {
chartArray[i] = obj[i];
}
I am trying to get this:
chartArray[0] = obj0;
chartArray[1] = obj1;
chartArray[2] = obj2;
chartArray[3] = obj3;
chartArray[4] = obj4;
chartArray[5] = obj5;
Upvotes: 0
Views: 68
Reputation: 5041
I really get the feeling you are asking the wrong question (see https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). The objects you refer to should be in an array in the first place
Upvotes: 0
Reputation: 1818
Assume that the index of for loop is 0:
You have this code:
chartArray[0] = obj[0];
in this code you try to push an elemento of an array named "obj" with index 0 to your chartArray in index 0.
to do what you want you must resolve the name of the object by adding a sequential number to the word "obj" to do so you can use eval().
Try:
for (var i = 0; i < numberOfCountries; i++) {
//for debug uncomment nexr line
//console.log("name:","obj"+i,"eval:",eval("obj"+i));
if(typeof eval("obj"+i) !== "undefined") return chartArray.push(eval("obj"+i));
}
if object named "obj"+i isn't defined the loop continue to next "Countrie" whitout add to your array.
bye.
Upvotes: 0
Reputation: 7618
May be you want this?
for (var i=0; i<numberOfCountries; i++) {
chartArray.push(this["obj"+i]);
}
Upvotes: 1
Reputation: 78535
Assuming the obj
variables are available at window scope:
for (var i=0; i<numberOfCountries; i++) {
chartArray[i] = window["obj"+i];
}
Upvotes: 1
Reputation: 1570
you can do this:
var char = new Array();
for (var i = 0; i < number; i++)
{
char.push(obj[i]);
}
Upvotes: -1