I have a large numbers of variables. What is the most correct way to calculate the sum. Below is the static way. .What if the numbers will increase to N times?
function abc(a,b,c,d){
alert(a+b+c+d);
}
abc(2,3,4,5);
I have a large numbers of variables. What is the most correct way to calculate the sum. Below is the static way. .What if the numbers will increase to N times?
function abc(a,b,c,d){
alert(a+b+c+d);
}
abc(2,3,4,5);
function abc(){
return Array.prototype.reduce.call(arguments, function(a,b) {
return a + b;
}, 0);
}
We can reduce the verbosity by binding .reduce as the this value of .call.
var reduce = Function.call.bind([].reduce);
Then it's just:
function abc(){
return reduce(arguments, function(a,b) {
return a + b;
}, 0);
}
You could use arguments
function abc(){
var total = 0;
for( var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
alert(total);
}
abc(1, 2, 3, 4, 5, 6, 7);
OR
function abc( args ){
var total = 0;
for( var i = 0; i < args.length; i++) {
total += args[i];
}
alert(total);
}
abc([1, 2, 3, 4, 5, 6, 7]);
The best way would be to use the latter.
arguments array isn't deprecated in strict mode, but strict mode does change it and remove some behavior.arguments haven't been deprecated or removed. arguments.caller was, but it was replaced with arguments.callee.callerTo accept a limitless number of arguments automatically, use the arguments property.
function sum() { // javascript functions can accept more arguments than specified
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
Bear in mind that this might not actually be much shorter or more-readable than just calling "a + b + c + d" in your original code.
Here is a shorter version using the Array.reduce() command.
function abc() {
alert([].reduce.call(arguments, function(a, b) { return a + b; }));
}
abc(2,3,4,5);