【问题标题】:How to spread object as method input parameter but not as arguments array?如何将对象作为方法输入参数而不是作为参数数组传播?
【发布时间】: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


【解决方案1】:
test(...Object.values(input), 'other')

会有点工作,但当然,一旦对象获得更多属性或以不同的顺序包含它们,它就会中断 - 它不会将属性放入相应参数名称的参数中,这是不可能的。要获得正确的解决方案,您应该更改 test 函数以获取选项对象:

function test(options) {
   console.log('firstName: ', options.firstName):
   console.log('lastName: ', options.lastName):
   console.log('age: ', options.age):
}

或解构:

function test({firstName, lastName, age, otherThings}) {
   console.log('firstName: ', firstName):
   console.log('lastName: ', lastName):
   console.log('age: ', age):
}

然后你可以正确调用它

test(input)

或者也可以使用对象传播

test({...input, otherThings: 'other'})

【讨论】:

  • 谢谢!这有点工作,不幸的是我无法修改可以被视为不可更改接口的方法签名或实现,我只能在调用方进行更改..
  • 那你绝对应该使用test(input.firstName, input.lastName, input.age, 'other');
【解决方案2】:

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);
}

test.apply(this, Object.values(input));

您可以使用 apply 发送值。然而,对象键顺序并不能保证,所以这不是一个“很好”的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多