Is there an elegant way of calling a method on each object in an array without iteration?
Edit: The intent of the question was to ask "without a for loop, or without any iteration if possible" Sorry for the confusion
var dogs = [new Dog("Max"), new Dog("Buddy"), new Dog("Charlie")];
for(var i=0; i<dogs.length; i++){
dogs[i].sayName();
}
function Dog(name){
this.name = name;
this.sayName = function(){
console.log(this.name);
}
}
Use .forEach()
dogs.forEach(function(elem) {
console.log(elem.sayName());
}
Alternatively you can use .map() , which returns a new array
dogs.map(function(elem) {
return elem.name;
}
If you are using array.map() you should return something so you don't end up with a new array of undefined values, if you intend on using the returned array.
Using forEach() seems like a better fit in your use case.
However as @Barmar points out, both methods still iterate over each element in the array.
Doing something on each array item means you iterate the array.
So it's not possible to do it without iterating the array.
You can use map :
dogs.map(function(thisDog) { thisDog.sayName(); })
The callback for map
takes three arguments: the current value, the current index, and the array. But in your case you only need the current value so you don't need to provide the other two arguments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.