javascript - Add values to an array -


how add values empty array? have tried following not working:

var student = [{}]; (var = 0; < 5; i++) {     student[i].name = i;     student[i].id = "1";     student.push(student[i]); }   var = json.stringify(student); alert(a); 

it give output 6 time repeated last values not 5 time :

'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]' 

var student = [{}]; 

this creates javascript array containing 1 empty object

student[i].name = i; student[i].id = "1"; 

for i = 0, alters empty object.

student.push(student[i]); 

you push altered object array exists in. have 2 identical values in array.

two items after first push. repeated 5 times.

pushing item adds array. there's no point in pushing element that's in array. create new object , push that. array doesn't have pre-populated empty object modify.

var student = []; (var = 0; < 5; i++) {     student.push({         name: i,         id: '1'     }); }  

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -