-
GCT1015
基本上你可以使用一个生成器函数,它可以通过自制限制来停止,就像在下面的函数中一样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,它将迭代生成器函数的迭代器
-
江户川乱折腾
您可以移交计数器并省略任何其他值以进行过滤。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));
-
慕娘9325324
您可以使用另一个变量来跟踪到目前为止与条件匹配的项目数,并且在达到限制后始终返回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}作为回调函数的上下文。
-
长风秋雁
只是为了诀窍:编辑:澄清此代码将选择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);
-
牧羊人nacy
你不能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;}
-
繁星点点滴滴
您可以定义自定义方法,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
-
ABOUTYOU
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)
-
UYOU
你无法阻止/破坏中间的过滤器。您可以做的是编写传统的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);