You can also use rest parameters:
function Numbers(...numbers){
this.numbers = numbers;
}
Answer from madox2 on Stack OverflowYou can also use rest parameters:
function Numbers(...numbers){
this.numbers = numbers;
}
Using a spread does the same thing cleaner in ES2015
this.numbers = [...arguments];
Just remember that this won't work in arrow functions (no arguments), and you're good. Rest arguments and Array.from are other options that are fine as well.
The old-fashioned ES5 is:
this.numbers = [].slice.call(arguments);
Although the other answers are correct, they change the function signature to accept an object instead of 2 separate arguments. Here is how to use an object's values as function arguments without altering the function's signature. This requires Object.values (ES 2017) and the spread operator to be available in your runtime.
const args = {
a: 1,
b: 2
}
const fn = (a, b) => a + b
fn(...Object.values(args));
Keep in mind this will work only in your specific case, since Object.values returns the values of all object keys and doesn't guarantee alphabetical sort order. If you want to take only the values of properties which are named a and b, you can map over Object.keys(args) and filter only those values.
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))