2020年1月18日土曜日

Custom reduce function to Javascript Allay class

learn how to use Javascript prototype.
let's make a reduce() function of  Allay class using  javascript prototype.


Array.prototype.myReduce = function(callback, initVal) { 
 let acc = initVal; 
  for (i = 0; i < this.length; i++) { 
   acc = callback(acc, this[i]); 
  }; 
 return acc
}


let myArray = [1,2,3]
myArray.myReduce((acc, elem) => { return acc + elem; }, 0)
6


What is reduce() function 

from mozira document of reduce

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));

// expected output: 15



0 件のコメント:

コメントを投稿