2015-06-27 43 views
0

我需要讓結果出來作爲了和增加新的對象值到現有對象的值再次超過

{ 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

您的問題看起來是在addFriend(animal, animal2),您設置animal2 = animal。我認爲你想要做的是追加朋友,可以像

function addFriend(animal, animal2) { 
    var pastFriends=animal.friends; 
    pastFriends.push(animal2); 
    animal.friends = pastFriends; 
} 
+0

非常感謝你! – jyoon006