Am trying to read only very first element of friends array and add it to matches array for each object. If I add matches property directly on object. Then it returns expected result. But if I use a function addmatches to add matches array property. Then matches array value is coming same for each animal object.
var AnimalCreator = function(username, species, tagline, noises) {
var friends = [];
//var matches = [];
return {
username: username,
species: species,
tagline: tagline,
noises: noises,
friends: friends,
//matches: matches
}
};
var sheep = AnimalCreator('Cloud', 'sheep', 'You can count on me!', ['baahhh', 'arrgg', 'chewchewchew']);
var rabbit = AnimalCreator('Sky', 'Rabbit', 'I like jumping!', ['haha', 'heehee']);
var tiger = AnimalCreator('Tim', 'Tiger', 'I am strong!', ['Grrrr', 'grrrrrr!']);
var bear = AnimalCreator('Poo', 'Bear', 'I am your friend', ['wowo', 'whwhwh']);
var addFriend = function(animal, friend) {
animal.friends.push(friend.username);
};
addFriend(sheep, rabbit);
addFriend(sheep, tiger);
addFriend(tiger, bear);
var myFarm = [sheep, rabbit, tiger, bear];
var addmatches = function(farm){
var matches = [];
for(var i=0;i < farm.length; i++){
farm[i].matches = matches;
}
};
addmatches(myFarm);
var giveMatches = function(farm) {
for (var i = 0; i < farm.length; i++) {
if (farm[i].friends.length > 0) {
farm[i].matches.push(farm[i].friends[0]);
}
}
};
giveMatches(myFarm);
console.log(myFarm);
addMatchesfunction supposed to do? As of right now, assigning the samematchesarray to every animal is exactly what it does, and that's all it does.