手写forEach
Array.prototype.myforEach = function (fn, thisValue) {
let index = 0;
let arr = thisValue || this;
if (typeof fn !== 'function') {
throw new TypeError(fn + 'is not a function')
}
while (index < arr.length) {
if (index in arr) {
fn.call (thisValue, arr[index], index, arr)
}
index ++
}
};
let arr = [1, 3, 5, 7]
arr.myforEach((item, i , arr) =>{
console.log('item:' + item + 'i:' + i)
})
手写map方法
Array.prototype.mymap = function(fn,thisValue){
let arr = thisValue || this
let index = 0
let newArr = [];
if(typeof fn !== 'function'){
throw new TypeError(fn + 'is not function')
}
while(index<arr.length){
if(index in arr){
let result = fn.call(thisValue, arr[index], index, arr)
newArr[index] = result //返回一个新数组
}
index++
}
return newArr
}
let arr = [1,3,5,7]
let newArr = arr.mymap((item)=>{
return item*3
})
console.log(newArr)
手写filter方法
Array.prototype.myFilter=function(callback, context=window){
let len = this.length
newArr = [],
i=0
for(; i < len; i++){
if(callback.apply(context, [this[i], i , this])){
newArr.push(this[i]);
}
}
return newArr;
}
手写every方法:
every方法参数:
Array.prototype.myEvery=function(callback, context = window){
var len=this.length,
flag=true,
i = 0;
for(;i < len; i++){
if(!callback.apply(context,[this[i], i , this])){
flag=false;
break;
}
}
return flag;
}