I am participating in the Mid-Autumn Festival Creative Submission contest. Please see:Mid-Autumn Festival Creative Submission Contest
Requirements:
Array.prototype.myreduce ()
Arr. Reduce (Callback [Accumulator, currentValue, Array], initialValue)
3. The parameters
CurrentValue current element currentIndex currentIndex optional parameter array array object optional parameter initialValue initialValue this parameter is optionalCopy the code
4. Return value: cumulative processing result of the function
Code:
Array.prototype.myReduce = function (callback, initialValue) { let arr = this; / / / var/shallow copy Array arr = Array. The prototype. Slice. Call (this); / / check if want to call this method is a array (this = = = null | | this = = = undefined) {/ / this is not present, Throw new TypeError(' array.prototype. reduce '+ 'called on null or undefined'); } // if (Object.prototype.toString.call(arr) ! == '[object Array]' || arr.length === 0) // return; if (! Array.isarray (this)) {throw (' Call object must be an Array '); } if (typeof callback ! = 'function') {throw (' accumulator must be a function type '); } // if (this.length === 0) { // return ; // } if (! Arr.length) {return} // If reduce() is called with init, pre takes the value init, and // cur takes the first value in the array; // If init is not provided, pre takes the first value in the array. // Cur takes the second value in the array. Arr [0] : initialValue // The index of the element being processed is 0 if init is provided, otherwise 1 let I = initialValue == undefined? 1:0; for (i; i < arr.length; i++) { pre = callback(pre, arr[i], i, arr); } return pre; }Copy the code
Validation:
Const res = [1, 2, 3, 4]. MyReduce ((pre, cur, index) => {return pre + cur; }, 1); console.log(res); / / 11Copy the code