Es6: What Happens If The Rest Parameter Is An Array?
if I have: function foo(number, ...args) { //foo to add args to sum } and I want a caller to be able to call foo like: foo(10, 1, 2, 3); // 16 or: foo(10, [1, 2, 3]); //16 Th
Solution 1:
You could use some recursion:
functionfoo(...args) {
var sum = 0;
args.forEach((arg) => {
if (!Array.isArray(arg))
sum += arg
else
sum += foo(...arg); // if it's an array, destructure
});
return sum;
}
With that code, you can even pass arrays inside arrays inside arrays if you want :)
Edit, with a for
loop:
functionfoo(...args) {
var sum = 0;
for (var arg of args) {
if (!Array.isArray(arg))
sum += arg
else
sum += foo(...arg); // if it's an array, destructure
};
return sum;
}
Solution 2:
Well you can convert the arguments to an array and concat them.
functionfoo(){
return [].concat.apply([],Array.prototype.slice.call(arguments)).reduce( function (p,c) { return p + c; }, 0);
}
var x1 = foo(10, [1,2,3]);
console.log(x1);
var x2 = foo(10,1,2,3);
console.log(x2);
Solution 3:
You can use .concat
with .apply
, and for sum .reduce
, like this
functionfoo(...args) {
return ([].concat.apply([], args)).reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
Solution 4:
for nested arrays recursion might work nicely. You can have only numbers or arrays or nested arrays or mixed.
functionadd() {
returnArray.prototype.reduce.call(arguments, function(p, c) {
if (Array.isArray(c)) {
return p + add.apply(null, c);
} else {
return p + c;
}
});
}
Post a Comment for "Es6: What Happens If The Rest Parameter Is An Array?"