在数组中的每个项目上调用方法的简洁方法

Clean way of calling method on each item in array

有没有比以下更好的方法来调用数组中的每个项目的方法:

_.each(items, function(item) {
    item.method();
});

在 Scala 中,您可以执行以下操作:

items.foreach(_.method())

想知道 javascript

中是否有类似的东西

也许尝试使用 built-in foreach?

items.forEach(function(item) {
    item.method();
});

目前浏览器支持 pretty much ubiquitous

是你不喜欢的匿名函数吗?我发现这比这个答案更具可读性,但如果你真的想避免它,并且每个项目都通过原型共享相同的 method,并且你知道至少有一个项目,你可以这样做以避免它:

_.each( items, items[0].method.call );

在 ES6 中你也可以使用 arrow function:

_.each( items, item => item.method() );

尝试使用 for 循环

for (var i=0;i<items.length;items[i++].method());

var items = [{
  method: function() {
    console.log(0)
  }
}, {
  method: function() {
    console.log(1)
  }
}];
for (var i = 0; i < items.length; items[i++].method());

如果你想使用一些lodash函数,我会给你那种函数式的方法。

_.each(items, _.method('method'));

_.method

因为你的问题是用 Underscore 标记的,它有一个很好的实用方法:_.invoke :

_.invoke(items, 'method')