如何将对象作为方法输入参数而不作为参数数组传播?

问题描述

我有一个期待乘法参数的函数一个输入对象,其中包含与键字段名具有相同键名的信息,举个小例子,例如

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,然后自动将它们映射到方法参数字段中,我知道...input可能不起作用,因为input是不是数组的对象,因此它是不可迭代的。

// is it possible?
test(...input.someAction?,'other');

当我的输入对象非常大并且想要找出一种无需修改方法签名的聪明方法时,这将有所帮助,请注意,我无法修改方法签名或实现,我们可以将其视为接口方法,并且我们只能确定如何在我们这边执行

解决方法

test(...Object.values(input),'other')

可以解决问题,但是当然,只要对象获得更多属性或以不同顺序包含它们,它将立即中断-不会将属性放入相应参数名称的参数中,这是不可能的。为了获得正确的解决方案,您应该更改test函数以使用一个options对象:

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'})
,

const input = {
   firstName: 'first',lastName: 'last',age: 19
}

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

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

您可以使用apply发送值。但是,不能保证对象键顺序,因此这不是一个“绝佳”的解决方案。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...