手写数组的 map 方法

2020-04-07  本文已影响0人  lovelydong
              Array.prototype.map=function(callbackFn,thisArg){
                //处理数组类型异常
                if(this === null || this === undefined){
                    throw new TypeError("Cannot read property 'map' of null or undefined"");
                }
                //处理回调类型异常
                if(Object.prototype.toString.call(callbackFn) != "[object Function]"){
                    throw new TypeError(callbackfn + ' is not a function');
                }
                //转换对象
                let Ob = Object(this);
                let t = thisArg;
                
                let len=Ob.length >>> 0;
                //这里解释一下, length >>> 0, 字面意思是指"右移 0 位",但实际上是把前面的空位用0填充,这里的作用是保证len为数字且为整数。
                let A = new Array(len);
                 for(let k =0; k < len; k++){
                    if(k in Ob){ //in 表示在原型链查找
                        let kValue = Ob[k];
                        //依次传入整个数组,当前项,当前索引,this
                        let mappedValue = callbackFn.call(T, hValue, k, Ob)
                        A[k] = mappedValue;
                    }
                 }
                 return A;
                
            }
上一篇 下一篇

猜你喜欢

热点阅读