这不是一个真实世界的例子,我过度简化了它.给这个数组:
const a = [1,2,3,4,5,6,7,8,4,5]; // Etc. Random numbers after.
Run Code Online (Sandbox Code Playgroud)
我想过滤它只有那些匹配一个模式(比如说这个简单的例子大于3),直到第一次追加(比方说元素大于7)
所以对于这个例子,我只想要:[4,5,6,7].但是filter,我会有尾随4和5:
const a = [1,2,3,4,5,6,7,8,4,5].filter((v) => v > 3)
// returns: [4, 5, 6, 7, 8, 4, 5]
Run Code Online (Sandbox Code Playgroud)
所以我想从一个数组中获取项目并在一个条件后最终停止.如何在第一次不满足条件后过滤然后停止?(没有for循环,我想保持它"功能性")
const a = [1,2,3,4,5,6,7,8,4,5,1,2,976,-1].awsome_function();
// returns: [4, 5, 6, 7, 8] because it stopped after the first 8.
Run Code Online (Sandbox Code Playgroud)
您可以使用Array#some并组合这两个条件.
var array = [1,2,3,4,5,6,7,8,4,5],
result = [];
array.some(a => (a > 3 && result.push(a), a > 7));
console.log(result);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
ES5
var array = [1,2,3,4,5,6,7,8,4,5],
result = [];
array.some(function (a) {
if (a > 3) {
result.push(a);
}
return a > 7;
});
console.log(result);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
如果你想保持功能风格,你可以使用这个:
Array.prototype.filterUntil = function(predicate, stop){
let shouldStop = false;
return this.filter(function filter(value, index){
if(stop(value)){
shouldStop = true;
}
return shouldStop && predicate(value);
});
}
Run Code Online (Sandbox Code Playgroud)
在你的情况下,你可以这样称呼它:
data.filterUntil(value => value > 3, value => value < 7)
Run Code Online (Sandbox Code Playgroud)