思考:
1、reduce 方法里面的参数都是什么作用?
2、push 和 pop 的底层逻辑是什么样的呢?
push 方法的底层实现
Array.prototype.push=function(...items){letO=Object(this);// ecma 中提到的先转换为对象let len =this.length >>>0;let argCount = items.length >>>0;// 2 ^ 53 - 1 为JS能表示的最大正整数if(len + argCount >2**53-1){thrownewTypeError("The number of array is over the max value")}for(let i =0; i < argCount; i++){O[len + i]= items[i];}let newLength = len + argCount;O.length = newLength;return newLength;}
Array.prototype.pop=function(){letO=Object(this);let len =this.length >>>0;if(len ===0){O.length =0;return undefined;}
len --;let value =O[len];deleteO[len];O.length = len;return value;}
其核心思路还是在于删掉数组自身的最后一个元素,index 就是数组的 len 长度,然后更新最新的长度,最后返回的元素的值,即可达到想要的效果。另外就是在当长度为 0 的时候,如果执行 pop 操作,返回的是 undefined,需要做一下特殊处理。
map 方法的底层实现
Array.prototype.map=function(callbackFn, thisArg){if(this===null||this=== undefined){thrownewTypeError("Cannot read property 'map' of null");}if(Object.prototype.toString.call(callbackfn)!="[object Function]"){thrownewTypeError(callbackfn +' is not a function')}letO=Object(this);letT= thisArg;let len =O.length >>>0;letA=newArray(len);for(let k =0; k < len; k++){if(k inO){let kValue =O[k];// 依次传入this, 当前项,当前索引,整个数组let mappedValue = callbackfn.call(T, KValue, k,O);A[k]= mappedValue;}}returnA;}
Array.prototype.reduce=function(callbackfn, initialValue){// 异常处理,和 map 类似if(this===null||this=== undefined){thrownewTypeError("Cannot read property 'reduce' of null");}// 处理回调类型异常if(Object.prototype.toString.call(callbackfn)!="[object Function]"){thrownewTypeError(callbackfn +' is not a function')}letO=Object(this);let len =O.length >>>0;let k =0;let accumulator = initialValue;// reduce方法第二个参数作为累加器的初始值if(accumulator === undefined){thrownewError('Each element of the array is empty');// 初始值不传的处理for(; k < len ; k++){if(k inO){
accumulator =O[k];
k++;break;}}}for(;k < len; k++){if(k inO){// 注意 reduce 的核心累加器
accumulator = callbackfn.call(undefined, accumulator,O[k],O);}}return accumulator;}
JS核心原理模块二 深入数组篇JS数组多个方法的底层实现思考: 1、reduce 方法里面的参数都是什么作用? 2、push 和 pop 的底层逻辑是什么样的呢?push 方法的底层实现Array.prototype.push = function(...items) { let O = Object(this); // ecma 中提到的先转换为对象 let len = this.length >>> 0; let argCount = items.l