【发布时间】:2020-12-23 00:31:51
【问题描述】:
我有一个函数需要乘法参数和一个输入对象,其中包含与参数字段名称相同的键名的信息,举个小例子,例如
const input = {
firstName: 'first',
lastName: 'last',
age: 19
}
function test(firstName, lastName, age, otherThings) {
console.log('firstName: ', firstName):
console.log('lastName: ', lastName):
console.log('age: ', age):
}
现在我必须通过输入对象的dot 表示法来调用它,或者使用变成数组的扩展然后在那里使用索引
// call method 1
test(input.firstName, input.lastName, input.age, 'other');
// call method - I know it's kinda ugly but just an available way
test(...[input][0], ...[input][1], ...[input][2], 'other');
我想知道是否有任何其他方式可以使用spread operator 的想法,但不是映射到数组中,而是将对象传播为flatMap,然后自动将它们映射到方法参数字段中,我知道@ 987654326@ 可能不起作用,因为 input 是一个对象而不是数组,因此它不可迭代。
// is it possible?
test(...input.someAction?, 'other');
当我的输入对象非常大并且想要找出一种在不修改方法签名的情况下执行它的智能方式时,这将有所帮助,请注意我不能修改方法签名或实现,我们可以将其视为接口方法和我们只能决定如何在我们这边执行它
【问题讨论】:
-
为什么不直接把对象作为参数呢?
-
也许改用 Python。更严重的是,不幸的是你不能在 JS 中做到这一点。
-
@HereticMonkey 因为我不能修改上面提到的方法签名或实现,可以认为是不可更改的接口。
标签: javascript ecmascript-6 named-parameters spread-syntax