在 _.invoke 源代码中,args 的作用是什么?

几个月前我刚刚开始学习 JS,我试图了解“_.invoke”源代码中的“args”在做什么。请问有大佬能解答一下吗?


我阅读了 mdn .apply 并阅读了其他 _.invoke 源代码,但无法理解。


  _.invoke = function (collection, functionOrKey, args) {

    if(typeof functionOrKey === "string") {

      return _.map(collection, function(item) {

        return item[functionOrKey].apply(item, args);

      });

    }

    else return _.map(collection, function(item) {

      return functionOrKey.apply(item, args);

    });

  };

测试功能是这样的:


_.invoke(['dog', 'cat'], 'toUpperCase');

      });


      it('runs the specified method on each item in the array, and returns a list of results', function() {

        var upperCasedStrings = _.invoke(['dog', 'cat'], 'toUpperCase');


        expect(upperCasedStrings).to.eql(['DOG', 'CAT']);

在测试函数中,没有“参数”,为什么!?


撒科打诨
浏览 220回答 1
1回答

HUH函数

发生的所有事情是您将一个参数或参数数组应用于用于映射集合的函数 - 所有三个都是传递给函数的参数。它类似于您可能在 Lodash/Underscore.js 等库中找到的其他方法——它本质上是一个自定义映射函数,您可以在其中传递参数,如下所示:let mapped = _.invoke(arr, aFunc, ["anArgument", 2]);如果没有传递参数,则传递的函数不需要参数 -toUpperCase不需要参数,所以不需要参数 - 因此没有传递。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript