gpt4 book ai didi

javascript - 如何在声明无法更改的函数中将对象作为单个参数传播?

转载 作者:行者123 更新时间:2023-12-01 23:34:01 25 4
gpt4 key购买 nike

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

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

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

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) 将无法运行。是的,永远不会调用该函数。对象传播和可迭代传播之间存在区别。参数和数组使用可迭代传播,这意味着必须满足两个条件:首先,您要传播的值必须是non-nullish。 ;其次,值必须是可迭代的,即具有 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 - 如何在声明无法更改的函数中将对象作为单个参数传播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65860630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com