一遍又一遍地将新对象值添加到现有对象值

时间:2015-06-27 19:56:08

标签: javascript function object

我需要编写一个代码,以便结果显示为

{ username: 'Cloud', 
  species: 'sheep', 
  tagline: 'You can count on me!', 
  noises: ['baahhh', 'arrgg', 'chewchewchew'], 
  friends: [{username: 'Moo', species: 'cow'...}, {username: 'Zeny', species: 'llama'...}]
}

但我的代码当前首先打印为添加到现有对象上的新对象,当我尝试将另一个新对象添加到现有对象和console.log时,它替换最后添加的对象并仅添加新对象值。

{ username: 'Cloud',
  species: 'sheep',
  tagline: 'You can count on me!',
  noises: [ 'baahhh', 'arrgg', 'chewchewchew' ],
  friends: 
   { username: 'Moo',
     species: 'cow',
     tagline: 'asdf',
     noises: [ 'a', 'b', 'c' ],
     friends: [] } }
{ username: 'Cloud',
   species: 'sheep',
   tagline: 'You can count on me!',
   noises: [ 'baahhh', 'arrgg', 'chewchewchew' ],
   friends: 
    { username: 'Zeny',
      species: 'llama',
      tagline: 'qwerty',
      noises: [ 'z', 'x', 'c' ],
      friends: [] } }

到目前为止,这是我的代码。我只把animal2 =动物写成它替换它,这样当添加另一个新的对象值时,它会将它添加到该对象中,而不是原始对象中。我需要在这里使用循环才能完成这项工作吗?

function AnimalCreator(username, species, tagline, noises) {
  var list = { 
    username: username,
    species: species,
    tagline: tagline,
    noises: noises,
    friends: []
  };

    return list;

}

function addFriend(animal, animal2) {

    animal.friends = animal2;
    animal2 = animal;


}

var sheep = AnimalCreator('Cloud', 'sheep', 'You can count on me!', ['baahhh', 'arrgg', 'chewchewchew']);
var cow =  new AnimalCreator('Moo', 'cow', 'asdf', ['a', 'b','c']);
addFriend(sheep, cow);
console.log(sheep);
var llama = new AnimalCreator('Zeny', 'llama', 'qwerty', ['z', 'x', 'c']);
addFriend(sheep,llama);
console.log(sheep);

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的问题似乎位于addFriend(animal, animal2),您设置了animal2 = animal。我认为你要做的是追加可以像

那样完成的朋友
function addFriend(animal, animal2) {
    var pastFriends=animal.friends;
    pastFriends.push(animal2);
    animal.friends = pastFriends;
}
相关问题