There are many online questions about sum (1) (2) (3), SUM (All-in-one) that require the same result 6 and requirements can meet the extension, that is, there are multiple parameters can also meet the requirements of the problem, so I wrote some examples can meet the requirements of these surface questions
<! DOCTYPE html>
<meta charset= "UTF-8";
<title> Document</title>
<body>
<script>
//Case 1
//sum (2,3) and SUM (2) (3) can all output outPut5, which is a simple question, as long as a function is returned, and the ES6 syntax is used in this example
//function sum (x=0,y) {
//if ([... arguments][1]==undefined) {
/let befor = [... arguments][0];
//return function Suum (afte) {
//let sum2 = Befor+afte;
//Console.log (' output${sum2} ');
//}
//}
//else{
let sum1 = X+y;
//Console.log (' output${sum1} ');
//}
//}
//
//SUM (2,3), output OUTPUT5
//SUM (2) (3), output OUTPUT5
//Case two, add (2,3,4 ...) and add (2) (3) (4) ... Solutions that both output the same results
function Add (x) {
var sum = x;
var tmp = function (y) {
sum = sum + y;
return TMP;
// };
tmp.tostring = function () {
return sum;
// };
return TMP;
// }
Console.log (Add (1) (2) (3)); 6
Console.log (Add (1) (2) (3) (4)); 10
Console.log (Add (1) (2) (3) (4) (5));//15
Console.log (Add (1) (2) (3) (4) (5) (6));//21
//Expansion Case 3, this function uses ES6 to implement input sum (), SUM (2,3,4 ...) Multiple values are added, plus sum (2) (3) (4) ... This case is also the most complete solution when multiple values are added equal to each other
function sum (.... args) {
if ([... args].length==1) {
Let sum2 = [... args][0];
var suum = function (y) {
Sum2 +=y;
Console.log (' Output ${sum2} ')
return suum;
}
suum.valueof = function () {
return sum2;
}
return suum;
}
else{
let sum1 = 0;
for (var i = 0;i<[...args].length;i++) {
Sum1 + = [... args][i];
}
Console.log (' outPut1 ${sum1} ');
}
}
SUM (); OUTPUT1 0
SUM (2,3,4);//OUTPUT1 9
SUM (2) (3) (4) (5);//OUTPUT1 5//OUTPUT1 9//OUTPUT1 14
The sum is output once per additional time. If you do not want to output three times, you can add a valueof method or ToString method to the function. Then remove the console from the Summ function.
then Console.log (SUM (2) (3) (4) (5));
//Interested friends can directly copy and paste to see the effect can be
</script>
</body>
JS in sum (2) (3) (4) returns 9 and sum (2,3) and SUM (2) (3) Return 5 and require extensibility