使用Javascript过滤函数输出,只要它们为真(Javascript算法)



问题

给定数组arr,从第一个元素(0索引(开始遍历并移除每个元素,直到函数func在遍历元素时返回true。

然后在满足条件后返回数组的其余部分,否则,arr应作为空数组返回。

这就是我尝试的

function dropElements(arr, func) {
let filteredArray = arr.filter((item) => {
return func(arr[item]) == true;
})
if (filteredArray == true) {
return filteredArray;
} else {
return [];
}
}
console.log(dropElements([1, 2, 3, 4], function(n) {
return n > 5;
}));
console.log(dropElements([1, 2, 3, 4], function(n) {
return n >= 3;
}))

如果要使用filter,请设置一个在遇到条件时切换的标志,如果切换了该标志,则返回true:

function dropElements(arr, func) {
let found = false;
return arr.filter((item) => {
if (found) return true;
if (func(item)) {
found = true;
return true;
}
});
}
console.log(dropElements([1, 2, 3, 4], function(n) {
return n > 5;
}));
console.log(dropElements([1, 2, 3, 4], function(n) {
return n >= 3;
}))

不过,我认为findIndexslice会更合适:

function dropElements(arr, func) {
const startAtIndex = arr.findIndex(func);
return startAtIndex === -1
? []
: arr.slice(startAtIndex);
}
console.log(dropElements([1, 2, 3, 4], function(n) {
return n > 5;
}));
console.log(dropElements([1, 2, 3, 4], function(n) {
return n >= 3;
}))

最新更新