javascript - 如何在我无法更改其声明的函数中将对象作为单个参数传播?
问题描述
我有一个具有一些属性的对象,例如;
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>)
你有什么想法吗?
解决方案
如果您无法更改函数的参数列表,则必须定义参数的预期顺序,然后将您的对象映射到此顺序:
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);
推荐阅读
- javascript - 是否有任何库可以让我查看 PDF 并添加自定义右键单击选项?
- javascript - 避免每次刷新页面时keycloak回调过程
- sql-server - Gitlab CI 无法连接到 ASP .Net Core APP 上的 Azure SQL Server
- android - 在 gms 视觉中加载 com.google.android.gms.dynamite.DynamiteModule$LoadingException 时出错
- javascript - Firebase如何链接使用phoneNumber创建的帐户
- python - Python 使用文件字节访问 zip 文件并遍历每个文件以将它们保存到数据帧中返回未找到文件的错误
- c++ - 带有引用的对象的 STL 容器
- git - 自动解决樱桃挑选冲突是否可能?
- microsoft-graph-api - MS Graph - SharePoint 错误:未添加成员
- python - 循环三个列表以创建组合输出?