The question about reduce ()
function getSum(total, num) {
return total + Math.round(num);
}
function myFunction(numbers) {
return numbers.reduce(getSum, 0);// 24
return numbers.reduce(getSum);// 23.5
}
myFunction([15.5, 2.3, 1.1, 4.7]);
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);// 125
document.getElementById("demo").innerHTML = numbers.reduce(getSum);// 125
}
if you do not specify the default value, the total parameter will be the first number in the first round of calculation.
[15.5, 2.3, 1.1, 4.7]
here is equivalent to 15.5, which is the first total (does not participate in rounding), and then keeps adding the number rounded later, and the result is 23.5. If the default value of total is set to 0, it rounds all the subsequent numbers and adds them up, so it is 24.
.
There is no need to answer the second question, and you must know it, because it is full of integers and there will be no difference.
first explain the parameters of the reduce function:
callback
:
The - accumulator
accumulator accumulates the return value of the callback; it is the cumulative value returned when the callback was last called, or initialValue (shown below).
The element being processed in the - currentValue
array.
- currentIndex optional
the index of the current element being processed in the array. If initialValue, is provided, the index number is 0, otherwise the index is 1.
- array optional
Array calling reduce
initialValue optional
callback reduce
return value
The
document also has an implementation of polyfill, which can be understood by looking at the implementation.
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, 'reduce', {
value: function(callback /*, initialValue*/) {
if (this === null) {
throw new TypeError( 'Array.prototype.reduce ' +
'called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback +
' is not a function');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// Steps 3, 4, 5, 6, 7
var k = 0;
var value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in o)) {
kPP;
}
// 3. If len is 0 and initialValue is not present,
// throw a TypeError exception.
if (k >= len) {
throw new TypeError( 'Reduce of empty array ' +
'with no initial value' );
}
value = o[kPP];
}
// 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// accumulator, kValue, k, O ).
if (k in o) {
value = callback(value, o[k], k, o);
}
// d. Increase k by 1.
kPP;
}
// 9. Return accumulator.
return value;
}
});
}