首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将新的对象值一次又一次地添加到现有的对象值中

将新的对象值一次又一次地添加到现有的对象值中
EN

Stack Overflow用户
提问于 2015-06-27 19:56:08
回答 1查看 36关注 0票数 0

我需要写一段代码,这样结果就会像

代码语言:javascript
复制
{ 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时,它将替换最后一个添加的对象,并且只添加新的对象值。

代码语言:javascript
复制
{ 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 = object来替换它,这样当添加另一个新的对象值时,它就会将它添加到该对象中,而不是原始对象中。我需要在这里有一个循环才能完成这项工作吗?

代码语言:javascript
复制
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);

我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-27 20:03:47

您的问题似乎是在addFriend(animal, animal2)中设置了animal2 = animal。我认为你想做的是附上朋友,这样做就像

代码语言:javascript
复制
function addFriend(animal, animal2) {
    var pastFriends=animal.friends;
    pastFriends.push(animal2);
    animal.friends = pastFriends;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31092926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档