[英]Javascript: Calling method of each object in array without iteration
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 编辑:问题的目的是问“没有for循环,或如果可能的话没有任何迭代”抱歉
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() 使用.forEach()
dogs.forEach(function(elem) {
console.log(elem.sayName());
}
Alternatively you can use .map() , which returns a new array 或者,您可以使用.map() ,它返回一个新数组
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. 如果您正在使用array.map(),则应返回某些内容,这样,如果打算使用返回的数组,则不会以未定义值的新数组结尾。
Using forEach() seems like a better fit in your use case. 使用forEach()似乎更适合您的用例。
However as @Barmar points out, both methods still iterate over each element in the array. 但是,正如@Barmar指出的那样,这两种方法仍会遍历数组中的每个元素。
Doing something on each array item means you iterate the array. 对每个数组项执行操作意味着您需要迭代数组。
So it's not possible to do it without iterating the array. 因此,不对数组进行迭代就不可能做到这一点。
You could use forEach
. 您可以使用
forEach
。 Even the object initialisation could be done in a similar way with map
: 甚至可以使用
map
以类似的方式完成对象初始化:
var dogs = ['Max','Buddy','Charly'].map(name => new Dog(name)); dogs.forEach(dog => dog.sayName()); function Dog(name){ this.name = name; this.sayName = function(){ console.log(this.name); } }
dogs.map(function(thisDog) { thisDog.sayName(); })
The callback for map
takes three arguments: the current value, the current index, and the array. map
的回调带有三个参数:当前值,当前索引和数组。 But in your case you only need the current value so you don't need to provide the other two arguments. 但是在您的情况下,您只需要当前值,因此不需要提供其他两个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.