admin管理员组文章数量:1333201
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);
Share
Improve this question
asked Jul 27, 2013 at 19:46
user2265582user2265582
2
- 8 Why don't you use an array instead of a large number of variables? Will make adding up easy. – Patrick Kostjens Commented Jul 27, 2013 at 19:47
- 1 Where are the numbers ing from? User input? – grandinero Commented Jul 27, 2013 at 19:49
4 Answers
Reset to default 4function 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);
Demo
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]);
Demo
The best way would be to use the latter.
To 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()
mand.
function abc() {
alert([].reduce.call(arguments, function(a, b) { return a + b; }));
}
abc(2,3,4,5);
本文标签: functionThe best way to sum up lots of numbers using JavaScriptStack Overflow
版权声明:本文标题:function - The best way to sum up lots of numbers using JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742285824a2446907.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论