微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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发送值。但是,不能保证对象键顺序,因此这不是一个“绝佳”的解决方案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?