我想做一个可以接受任意数量参数的函数。我可以使用fix参数来使函数起作用,但是无法使用n个参数来解决。
示例:
const first = { x: 2, y: 3};
const second = { a: 70, x: 4, z: 5 };
const third = { x: 0, y: 9, q: 10 };
const firstSecondThird = extend(first, second, third);
// { x: 2, y: 3, a: 70, z: 5, q: 10 }
const secondThird = extend(second, third);
// { a: 70, x: 4, z: 5, y: 9, q: 10 }`
答案 0 :(得分:1)
您可以使用Rest parameters将所有参数放入数组,然后在spread syntax内使用reduce
来递归合并它们:
const first = { x: 2, y: 3},
second = { a: 70, x: 4, z: 5 },
third = { x: 0, y: 9, q: 10 };
const extend = (...params) => params.reduce((r,p) => ({ ...r, ...p }), {})
console.log(extend(first, second, third))
console.log(extend(second, third))
如果要优先使用较早对象的属性,则必须先reverse
arguments
,然后再使用reduce
:
const first = { x: 2, y: 3},
second = { a: 70, x: 4, z: 5 },
third = { x: 0, y: 9, q: 10 };
const extend = (...params) => params.reverse().reduce((r, p) => ({ ...r, ...p}), {})
console.log(extend(first, second, third))
console.log(extend(second, third))