如何将对象作为参数散布到函数中? [英] how to spread an object to a function as arguments?
本文介绍了如何将对象作为参数散布到函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象和一个接受参数的函数,我想扩展对象,以便每个属性都是该函数中的一个参数.
I have an object an a function which accept arguments, I would like to spread the objects so each property is an argument in that function.
我的代码在做什么错了?
What am I doing wrong in my code?
const args = {
a: 1
b: 2
}
const fn = (a, b) => a + b
// i am trying with no success
console.log(fn(...args))
推荐答案
You can use ES6 object destructuring
on passed parameter and then just pass your object.
const args = {a: 1, b: 2}
const fn = ({a, b}) => a + b
console.log(fn(args))
您还可以为这些属性设置默认值.
You can also set default values for those properties.
const args = {b: 2}
const fn = ({a = 0, b = 0}) => a + b
console.log(fn(args))
这篇关于如何将对象作为参数散布到函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文