一天一个仿lodash函数实现-fill、findIndex、first、head
把arr数组中从start到end(不包括end)用value填充
function fill(arr, value, start = 0, end = arr.length) {
for(let i = start;i<end;i++) {
arr[i] = value;
}
return arr
}
findIndex
function findIndex(arr, predicate, fromIndex=0) {
let result = -1;
for(let i=fromIndex;i<arr.length;i++) {
if(predicate(arr[i])){
result = i;
break;
}
}
return result
}
findLastIndex
function findLastIndex(arr, predicate, fromIndex=arr.length-1) {
let result = -1;
for(let i=fromIndex;i>=0;i--) {
if(predicate(arr[i])){
result = i;
break;
}
}
return result
}
head
返回数组第一个元素
function head(arr){
return arr.length?arr[0]:undefined;
}