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

时间:2019-10-24 00:59:35

标签: javascript arrays function lodash

几个月前,我才刚刚开始学习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']);

在测试功能中,没有'args',为什么!?

1 个答案:

答案 0 :(得分:2)

所有发生的事情是您要获取一个参数或参数数组以应用于用于映射集合的函数-这三个参数都是传递给该函数的参数。

它类似于您在Lodash / Underscore.js之类的库中可能找到的其他方法-本质上是一个自定义映射函数,您可以在其中传递参数,如下所示:

MimeMessage eml = MimeMessage.Load(savedEmlFullFilePath);
EmailMessage mail = new EmailMessage(service);

foreach (var attachment in eml.Attachments)
{
    using (var stream = File.Create(AppConfig.EmailSaveFilePath + "attachment_from_email"))
    {
        if (attachment is MessagePart)
        {
            var part = (MessagePart)attachment;

            part.Message.WriteTo(stream);

            mail.Attachments.AddFileAttachment(AppConfig.EmailSaveFilePath + "attachment_from_email");
        }
        else
        {
            var part = (MimePart)attachment;

            part.Content.DecodeTo(stream);

            mail.Attachments.AddFileAttachment(AppConfig.EmailSaveFilePath + "attachment_from_email");
        }
    }
}

如果不传递任何参数,则传递的函数不需要参数-let mapped = _.invoke(arr, aFunc, ["anArgument", 2]); 不需要参数,因此不需要参数-因此不传递参数。