如果条件只能满足一次,如何停止数组方法?

How to stop an array method if the condition must only satisfied once?

我给出了一个简单的任务来遍历数组 arr 并从第一个元素(0 索引)开始删除每个元素,直到函数 func returns true 当迭代元素通过它时。

则return数组的其余部分"once"满足条件,否则arr应return为空数组。所以 dropElements([0, 1, 0, 1] 应该 return [1, 0, 1].

为了回答我的问题,我使用数组过滤方法,但下面的代码将 return [1, 1]。是否可以在这个问题中停止数组方法?一旦条件 return 为真,我应该在我的代码中添加什么来停止它?

function dropElements(arr, func) {
  return arr.filter(func);
}

dropElements([0, 1, 0, 1], function(n) {return n === 1;});

我会使用 findIndex 来查找与条件匹配的索引,然后 .slice 只取它后面的内容:

function dropElements(arr, func) {
  const index = arr.findIndex(func);
  return index === -1 ? [] : arr.slice(index);
}

console.log(dropElements([0, 1, 0, 1], n => n === 1));