underscore.js中_.each方法和_.invoke方法的区别

7
我无法理解underscore js方法_.each_.invoke之间的区别。
两者似乎都会在每个项目上调用传递的函数。
在什么情况下应该使用_.each_.invoke
请提供一些示例以说明区别。
1个回答

9
不,它们做不同的事情。看一下它们的代码!
  • each calls a given function with each element of a given object. You can additionally pass it a context on which the functions are applied. It acts like the native forEach on arrays.

    iterator.call(context, obj[i], i, obj)
    

    It does return undefined.

  • invoke usually gets a method name as a string, and looks up the method dynamically for each element of the given set. Then it applies the method on that element; and you additionally can pass it some arguments.

    (_.isFunction(method) ? method : obj[i][method]).apply(obj[i], args);
    

    It does return the results of the invocations, it basically does map.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接