我需要写一段代码,这样结果就会像
{ 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 = object来替换它,这样当添加另一个新的对象值时,它就会将它添加到该对象中,而不是原始对象中。我需要在这里有一个循环才能完成这项工作吗?
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);我做错了什么?
发布于 2015-06-27 20:03:47
您的问题似乎是在addFriend(animal, animal2)中设置了animal2 = animal。我认为你想做的是附上朋友,这样做就像
function addFriend(animal, animal2) {
var pastFriends=animal.friends;
pastFriends.push(animal2);
animal.friends = pastFriends;
}https://stackoverflow.com/questions/31092926
复制相似问题