9 回答

TA贡献1827条经验 获得超4个赞
基本上你可以使用一个生成器函数,它可以通过自制限制来停止,就像在下面的函数中一样
function *filter(array, condition, maxSize) {
if (!maxSize || maxSize > array.length) {
maxSize = array.length;
}
let count = 0;
let i = 0;
while ( count< maxSize && i < array.length ) {
if (condition(array[i])) {
yield array[i];
count++;
}
i++;
}
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log( Array.from( filter(array, i => i % 2 === 0, 2 ) ) ); // expect 2 & 4
因此它会在达到maxSize作为参数后停止,并且很容易将其返回到数组中,您可以使用Array.from,它将迭代生成器函数的迭代器

TA贡献1851条经验 获得超5个赞
您可以移交计数器并省略任何其他值以进行过滤。
const
filter = v => v % 2,
filterMax = (fn, c) => x => c && fn(x) && c--,
max = 3,
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
result = array.filter(filterMax(filter, max));
console.log(result);
将Icepickle的答案提前一点,用循环找到下一个有效项并产生这个。
function* filterMax(array, cb, count) {
var i = 0;
while (count) {
while (i < array.length && !cb(array[i])) i++;
if (i >= array.length) return;
yield array[i++];
count--;
}
}
const
filter = v => v % 2,
max = 3,
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(...filterMax(array, filter, max));

TA贡献1783条经验 获得超4个赞
您可以使用另一个变量来跟踪到目前为止与条件匹配的项目数,并且在达到限制后始终返回false。这是一个例子:
const arr = [1,0,2,0,3,0,4,5,6,7,8,9,10,11,12,13,14];
const filtered = arr.filter(function(item) {
if (this.count < 10 && item > 0) {
this.count++;
return true;
}
return false;
}, {count: 0});
console.log(filtered);
在这里,我使用一个对象{count: 0}
作为回调函数的上下文。

TA贡献1757条经验 获得超7个赞
只是为了诀窍:
编辑:澄清此代码将选择10个第一个偶数列表
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
const result = array.reduce((temp, value) => {
if(value%2==0 && temp.length<10)
temp.push(value);
return temp;
}, []);
console.log(result);

TA贡献1862条经验 获得超7个赞
你不能break从Array.prototype.filter方法。它将遍历每个元素。您可以使用简单的for循环并在找到10个项目时中断
const items = []
for (const value of array) {
if (value.includes(term))
items.push(value)
if (items.length === 10)
break;
}

TA贡献1803条经验 获得超3个赞
您可以定义自定义方法,Array.prototype其中将包含2个参数。一个回调和结果数组的最大元素将包含。
下面的代码从数组中获取前3个奇数。
function filterUpto(callback,max){
let len = this.length
let res = [];
let i = 0;
while(res.length < max && i < len){
if(callback(this[i],i,this)) res.push(arr[i])
i++
}
return res;
}
Object.defineProperty(Array.prototype,'filterUpto',{
value:filterUpto
})
let arr = [1,2,3,4,5,6,7,8,9,10];
console.log(arr.filterUpto(x => x % 2,3)); //first three odd numbers

TA贡献1812条经验 获得超5个赞
var data = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14"]
var limited = data.filter((val,i)=>i<10)
console.log(limited)

TA贡献1878条经验 获得超4个赞
你无法阻止/破坏中间的过滤器。您可以做的是编写传统的for循环来遍历项目,然后在找到前10时中断。
我对这个问题的看法:
let items = [];
let required_count = 10;
let index = 0;
do{
if(array[index].indexOf(term) != -1){
items.push(array[index])
}
index += 1;
}while(items.length < required_count && index < array.length);
添加回答
举报