数组常见方法
push
js
Array.prototype.push=function(...items){
// 确保 this 是一个对象
let O=Object(this);
// >>> 是无符号右移操作符
// >>> 0 的作用是将 length 转换为一个合法的非负整数
let len=this.length>>>0;
let argCount=items.length>>>0;
// 2**53-1是JS能表示的最大正整数
if(len+argCount>2**53-1){
throw new TypeError('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;
}
pop
js
Array.prototype.pop=function(){
let O=Object(this);
let len=this.length>>>0;
if(len===0){
O.length=0;
return undefined;
}
len--;
let value=O[len];
delete O[len];
O.length=len;
return value;
}
map
js
Array.prototype.map=function(callbackFn,thisArg){
if(this===null||this===undefined){
throw new TypeError("Cannot read property 'map' of null");
}
if(Object.prototype.toString.call(callbackFn)!=='[object Function]'){
throw new TypeError(callbackFn+'is not a function');
}
let O=Object(this);
let T=thisArg;
let len=O.length>>>0;
let A=new Array(len);
for(let k=0;k<len;k++){
if(k in O){
let kValue=O[k];
// 依次传入this,当前项,当前索引,整个数组
let mappedValue=callbackFn.call(T,kValue,k,O);
A[k]=mappedValue;
}
}
return A;
}
reduce
js
Array.prototype.reduce=function(callbackFn,initialValue){
if(this===null||this===undefined){
throw new TypeError("Cannot read property 'reduce' of null");
}
if(Object.prototype.toString.call(callbackFn)!=='[object Function]'){
throw new TypeError(callbackFn+'is not a function');
}
let O=Object(this);
let len=O.length>>>0;
let k=0;
let accumulator=initialValue;
if(accumulator===undefined){
for(;k<len;k++){
if(k in O){
accumulator=O[k];
k++;
break;
}
}
throw new Error('Each element of the array is empty');
}
for(;k<len;k++){
if(k in O){
// 注意reduce的核心累加器
accumulator=callbackFn(accumulator,O[k],k,O);
}
}
return accumulator;
}