首页 > 解决方案 > 如何在我无法更改其声明的函数中将对象作为单个参数传播?

问题描述

我有一个具有一些属性的对象,例如;

integrationConfig = {
  iconEmoji: ':myIconEmoji:', 
  team: 'myTeam', 
  text: 'myText', 
  channel: 'myChannel', 
  botName: 'myBot'
}

我将此对象传递给如下所示的函数(attachments不重要)。

return await this.pushToSlack(...integrationConfig, attachments);

重要的是,这个函数是 NPM 包的一部分,所以我不想更改函数声明

函数声明如下:

exports.pushToSlack = function (channel, text, botName, iconEmoji, team, attachments, cb = function () {}) {
  // […]
}

我在函数上放了一些断点,pushToSlack但调试器没有跳到那行。我猜这个函数没有被调用。我也收到此错误:

Debug: internal, implementation, error 
    TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
    at Function.all (<anonymous>)

你有什么想法吗?

标签: javascriptfunctiondestructuring

解决方案


如果您无法更改函数的参数列表,则必须定义参数的预期顺序,然后将您的对象映射到此顺序:

const argumentOrder = [
    "channel",
    "text",
    "botName",
    "iconEmoji",
    "team"
  ];

// […]

return await this.pushToSlack(...argumentOrder.map((property) => integrationConfig[property]), attachments);

你得到的错误意味着它func(...integrationConfig)不起作用。是的,该函数永远不会被调用。对象传播和可迭代传播之间存在区别。参数和数组使用可迭代传播,这意味着必须满足两个条件:首先,您要传播的值必须是非空值;其次,该值必须是可迭代的,即具有 的东西Symbol.iterator。对象传播只检查第一个条件。

理论上,您可以将这样的符号属性添加到您的对象中,这将允许您使用原始语法:

const integrationConfig = {
    iconEmoji: ":myIconEmoji:",
    team: "myTeam",
    text: "myText",
    channel: "myChannel",
    botName: "myBot",
    *[Symbol.iterator](){
      yield this.channel;
      yield this.text;
      yield this.botName;
      yield this.iconEmoji;
      yield this.team;
    }
  };

// […]

return await this.pushToSlack(...integrationConfig, attachments);

推荐阅读