iteratively adding to an array of objects in Javascript
I am trying to create an object iteratively with the following structure:
var series = {
data: [{
name: 'some text',
y: 0
},
{
name: 'some other text',
y: 1
}]
}
Below is my code so far:
var series = {
data: []
};
var datatemp = {
y: '',
name: ''
};
for (var i=0; i<10; i++) {
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
But what I am getting is the final values of series.data[i].y and series.data[i].name in all elements开发者_如何学C of the array, rather than what I expect, which is different values as the counter i iterates. I would appreciate your guidance on what I am doing wrong. Thanks in advance!
To add to what Mimisbrunnr said, you could even do it this way:
for (var i=0; i<10; i++) {
series.data.push({y: i, name: "namelabel"+i});
}
There is no need for the intermediate variable.
You need to make a new datatemp for each iteration of the for loop otherwise you are just passing the same object into the array each time and modifying it's values.
for (var i=0; i<10; i++) {
var datatemp = {};
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
var series = {
data: []
};
for (var i=0; i<10; i++) {
var datatemp={};
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
for (var i=0; i<10; i++) {
console.log(series.data[i].y);
console.log(series.data[i].name);
}
http://jsfiddle.net/Vp8EV/
Objects are passed by reference in javascript, in your example you only have one object which is referenced by the name datatemp
, every time you assign a new value to one of its members the old member gets overwritten, so you have to create a new object for each iteration of the loop.
精彩评论