手写 every、map、some、reduce

实现every

function myEvery(fn,context){
	let arr  = Array.prototype.slice.call(this)
	if(arr.length==0){
		return true;
	}
	for(let i=0;i<arr.length;i++){
	 if(!arr.hasOwnProperty(i)) continue;
	 let res = fn.call(context,arr[i],i,this)
	 if(!res){
		return false
		}else{
		return true;
		}
	}
	return false;
}
Array.prototype.myEvery = myEvery;

测试

let res = [
  {
    name: "哈哈",
  },
  {
    name: "哈哈1",
  },
  {
    name: "哈哈",
  },
  {
    name: "哈哈",
  },
].myEvery((item, index, self) => {
  return item.name === "哈哈1";
});
console.log(res);//false

实现map

function myMap(fn,context){
	let arr = Array.prototype.slice.call(this);
	let mappedArr = []
	for(let i=0;i<arr.length;i++){
		//判断稀疏数组的情况
		if(!arr.hasOwnProperty(i)) continue;
		mappedArr[i] = fn.call(context,arr[i],i,this)
	}
	return mappedArr 
}
Array.prototype.myMap = myMap;

测试

[1, 8, 3, 4, { name: "ooo" }, , ,].myMap((item, index, self) => {
  console.log(item);
  //1
  //8
  //3
  //4
  //{name:'ooo'}
});

实现some

function mySome(fn,context){
 let arr = Array.prototype.slice.call(this);
 if(!arr.length) return false;
 for(let i=0;i<arr.length;i++){
 	//判断稀疏数组的情况
 	if(!arr.hasOwnProperty(i)) continue;
 	let res = fn.call(context,arr[i],i,this)
 	if(res){
 	return true;
    }
 }
 return false;
}
Array.prototype.mySome = mySome;

测试


let res = [1, 8, 3, 4, { name: "ooo" }, , ,].mySome(
  (item, index, self) => item >=8
);
console.log(res);//true

实现 reduce

function myReduce(fn,initValue){
 let arr = Array.prototype.slice.call(this)
 let res;
 let startindex;
 if(initValue===undefined){
	for(let i=0;i<arr.length;i++){
		if (!arr.hasOwnProperty(i)) continue;
	      startIndex = i;
	      res = arr[i];
	      break;
	}
 }else{
  res = initValue;
 }
 for (let i = ++startIndex || 0; i < arr.length; i++) {
    console.log(startIndex);
    if (!arr.hasOwnProperty(i)) continue;
    res = fn.call(null, res, arr[i], i, this);
  }
  return res;
}

测试

Array.prototype.myReduce = myReduce;
let sum = [1, 2, 3, 4].myReduce((prve, cur, index, arr) => {
  return prve + cur;
});
console.log(sum);//10

你可能感兴趣的:(javascript)