forEach:无返回值,单纯的遍历数组
Array.prototype.myForEach = function (callback) {//在数组的原型上添加myForEach方法,接收一个回调函数 for (let i = 0; i < this.length; i++) { let item = this[i];//定义回调函数接收的三个参数 let index = i; let array = this; callback(item, index, array)//调用回调函数 }}const arr = [{ id: 0, name: "我" }, { id: 1, name: "是" }]arr.myForEach((item, index) => { console.log(item);})
map: 创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果
/*** @param {callback} 回调函数* @param {thisArg} 执行 callback 函数时值被用作this。*/Array.prototype.myMap = function(callback,thisArg){ // 处理数组类型异常 if (this === null || this === undefined) { throw new TypeError("Cannot read property 'map' of null or undefined"); } // 处理回调类型异常 if (Object.prototype.toString.call(callback) != "[object Function]") { throw new TypeError(callback + ' is not a function') } let T = thisArg console.log(T); let A = new Array(this.length) for(let i = 0;i < this.length; i++){ //依次传入this, 当前项,当前索引 A[i] =callback.call(T,this[i],i) } return A}//callback == function(item,index){return item*item}let arr = [1,3,5,7,8,9]let res = arr.myMap((item,index) => { return item*item})console.log(res)
reduce
/** * @param {callback} * ruducer(callback)接受四个参数 accumulator currentValue index array * accumulator 表示累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue * currentValue 当前值 * index 当前索引 * array 调用reduce的数组 * @param {initialValue} * 作为第一次调用 callback函数时的第一个参数的值。如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。*///核心点 处理initialValue 返回值Array.prototype.myReduce = function(callback,initialValue){ if(this === null || this === undefined){ throw new Error("Cannot read property 'myReduce' of null or undefined") } if(Object.prototype.toString.call(callback) != "[object Function]"){ throw new Error(`${callback} is not a function`) } let arr = Array.prototype.slice.call(this); let res = initialValue ? initialValue : arr[0] if(res === undefined){ throw new Error('Each element of the array is empty'); } let startIndex = initialValue ? 0 : 1 //如果没有提供initialValue reduce从索引1开始执行callback,提供initialValue从0开始 for(let i = startIndex; i < arr.length; i++){ res = callback.call(null,res,arr[i],i,this) } return res}let arr = [1,3,5]let r = arr.myReduce((accumulator,currentValue) => { return accumulator * currentValue},0) //16console.log(r);