简体   繁体   中英

Javascript push with complex objects

I'm building an array of objects which have a property of type array:

here's some simplified code:

var _data = [];
for(var i=0;i<10;i++) {
  var element = {
        id: i,
        answers: []
  };

  for(var j=0;j<3;j++) {                        
    var answer = {
      id: j,
      description: ''
    };
   element.answers.push(answer);
  }
  _data.push(element);
}

At the end of the two cicle the array _data has 10 elements but each element has the property answer empty (I expect 3 items for each element). Why this happens? It seems like the push doesn't push the entire object but only the "first level properties". thanks

Running your code in Firefox 8 results in the following _data array:

_data:

[{id:0, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:1, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:2, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:3, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:4, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:5, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:6, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:7, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:8, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}, 
 {id:9, answers:[{id:0, description:""}, {id:1, description:""}, {id:2, description:""}]}]

Maybe you have a typo because it is answers not answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM