背景
来自关于 invoke 的文档方法,我读到:
Invokes the method named by methodName on each element in collection, returning an array of the results of each invoked method
因此,我假设以下代码是同义的,但事实并非如此:
_.map(items, function(item) {
return _.omit(item, 'fieldName');
})
_.invoke(items, _.omit, 'fieldName');
在这种情况下,invoke
方法生成一个字符串数组,而 map 方法返回一个项目数组,其中从每个项目中删除了 fieldName
。
问题
- 如何使用
invoke
方法获得与map
函数相同的结果? - 为什么
invoke
在这种特定情况下返回字符串数组?
var items = [{id:1, name:'foo'},
{id:2, name:'bar'},
{id:3, name:'baz'},
{id:4, name:'qux'}];
console.log(
_.invoke(items, _.omit, 'id')
);
console.log(
_.map(items, function(item) {
return _.omit(item, 'id');
})
);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.3.1/lodash.min.js"></script>
最佳答案
请务必记下您使用的是哪个版本的 lodash。
v4.11.1 使用 _.invokeMap
对集合进行操作时:
_.invokeMap([1,2,3], function () {
console.log(this)
})
关于javascript - _.invoke 方法在 Lodash 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28888777/