Javascript 将新对象值反复添加到现有对象值中
我需要写一个代码,这样的结果出来Javascript 将新对象值反复添加到现有对象值中,javascript,function,object,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'...}] } 但我的代码当前首先打印为
{ 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=animal写下来,它会替换它,这样当添加另一个新对象值时,它会将它添加到该对象中,而不是原始对象中。我需要在这里有一个循环才能工作吗
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);
我做错了什么?你的问题似乎在
添加朋友(动物,动物2)
你设置animal2=animal
的地方。我想你想做的是添加朋友,这可以像
function addFriend(animal, animal2) {
var pastFriends=animal.friends;
pastFriends.push(animal2);
animal.friends = pastFriends;
}