The problem is dry:
We'll pass you an array with two numbers. Returns the and of the two numbers and all the numbers between them.
The smallest number is not always at the front.
function SumAll (arr) {2 return 1; }5 SumAll ([1, 4]);
Functions that will be used
Math.max ()
Math.min ()
Array.reduce ()
Ideas:
(1) by Math.max (), math.min () extracts the maximum value in the array max and Min min;
(2) Create a new array to get the values between the minimum and maximum values;
(3) Use Array.reduce () to accumulate the new array.
Knowledge Points:
(1) Math.max (), math.min () cannot accept an array as a parameter,Math.max (array) does not exist ;
and apply is a method that fun.apply(thisArg, [argsArray])
all functions have, and fun
Thisarg is equivalent to what is specified when the function is run. this
值
-
argsArray
是
An array or class array object in which the array element is passed as a separate parameter to the
fun
function;
1 function Getmaxofarray (numarray) {2 return Math.max.apply (null, numarray); 3 }
This function can be implemented with a for loop, but it is too cumbersome.
(2) The reduce () method can operate on each element of an array, where value is the value of a single element, and sum is the cumulative value of those elements;
1 var total = Arr.reduce (function (sum, value) {2 return sum + value; 3 }, 0);
My Code:
1 functionSumAll (arr) {2 functionGetmaxofarray (numarray) {3 returnMath.max.apply (NULL, Numarray);4 }5 6 functionGetminofarray (numarray) {7 returnMath.min.apply (NULL, Numarray);8 }9 varMax =Getmaxofarray (arr);Ten varMin =Getminofarray (arr); One varArray = []; A - for(vari = min; I <= Max; i++) { -Arr[i-min] =i; the } - varTotal = Arr.reduce (function(sum, value) { - returnSum +value; -}, 0); + - returnTotal ; + } ASumAll ([1, 4]);
The FCC intermediate algorithm sums all the numbers