Noob to JS and underscore --
In the following simple code I am trying to iterate through var animalNames using underscore (_.each fxn) but when I run the code in Node in terminal it just goes right back to cmd prompt ie. nothing runs. Please help explain what's going.
function AnimalMaker(name) {
return { speak: function () { console.log("my name is ", name); } };
};
var animalNames = ['', '', ''];
var farm = [];
us.each(animalNames, function (name) {
farm.push(AnimalMaker(name));
});
Firstly, the map
method is more appropriate in this case, because you're mapping an array of names to an array of Animals
// I renamed AnimalMaker
// In JS it's a convention to capitalize constructors and keep normal functions camel-case
var createAnimal = function(name) {
return {
speak: function() { console.log("my name is", name); }
};
};
var names = ["Chicken", "Cow", "Pig"];
var animals = us.map(names, createAnimal);
With this code you've created a list of animals. Now you still need to make those animals speak:
us.each(animals, function(animal) {
animal.speak();
});
Or use invoke
to call a method for each object in a list:
us.invoke(animals, "speak");
Without underscore (native javascript in node.js) you could also write:
var animals = names.map(createAnimal);
animals.forEach(function(animal) {
animal.speak();
});