I am trying to understand MDN's documentation on .push() and .apply() because I'm having an issue where I am ending up with an array inside an array in a project. I have set up some experimental code to illustrate my problem.
Can anyone explain why the array contents inside foo()
print within another array? I am not understanding why it isn't printing one array for both console.log()
instances.
var animals = [];
var chickens = 'chickens';
var cows = 'cows';
animals.push(cows);
animals.push(chickens);
console.log(animals); // > Array ["cows", "chickens"]
function foo(...animals) {
console.log(animals); // > Array [["cows", "chickens"]] <-- why is this one inside another array?
};
I thought using .apply()
would solve the problem but it I couldn't get it to work. For example...
animals.push.apply(animals, cows);
animals.push.apply(animals, chickens);
// Error: second argument to Function.prototype.apply must be an array