// arr.fill(value, start, end);
Array.prototype.myFill = function (value, start = 0, end = this.length){
for(let i = start; i < end; i++){
this[i] = value;
}
}
二、实现filter方法
// arr.filter(function(item,index,arr){...},context)
Array.prototype.myFilter = function (fn, context) {
if(typeof fn !== 'function'){
throw new TypeError("arguments[0] is not a function");
}
let arr = this;
let res = [];
for(let i = 0; i < arr.length; i++){
if(fn.call(context, arr[i], i, arr)){
res.push(arr[i]);
}
}
return res;
}
三、实现find方法
// arr.find(function(item,index,arr){...}, context)
Array.prototype.myFind = function (fn, context) {
if(typeof fn !== 'function'){
throw new TypeError ("arguments[0] is not a function");
}
let arr = this;
for(let i = 0; i < arr.length; i++){
if(fn.call(context, arr[i], i, arr)){
return arr[i];
}
}
return undefined;
}
四、实现findIndex方法
// arr.findIndex(function(item, index, arr), context)
Array.prototype.myFindIndex = function (fn, context) {
if(typeof fn !== 'function'){
throw new TypeError("arguments[0] is not a function");
}
let arr = this;
for(let i = 0; i < arr.length; i++){
if(fn.call(context, arr[i], i, arr)){
return i;
}
}
return -1;
}