【问题标题】:Going through a for loop and rendering a subset of items from an array通过 for 循环并从数组中呈现项目的子集
【发布时间】:2021-03-22 14:18:47
【问题描述】:
这里是编码新手和第一次发布海报。如果之前已经回答过这个问题,我表示歉意,但我不确定无论如何我会查找它..
我正在经历一个从 api 中提取的数组的 for 循环渲染元素。我的目标是仅根据该数组的元素从该数组中打印 10 项(即不是数组的前 10 项,而是数组中符合条件的前 10 项)
类似这样的:
for(let i=0;i<json.length;i++)
{
let product = json[i]
let category = product.category
renderProduct() //this is a function that prints the product to the DOM
}
在我的 api 中,每个对象都有一个类别,假设有些是 X,有些是 Y,有些是 Z,有些是 Q,等等....我希望能够打印前 10 个 X -希望这是有道理的,感谢大家的帮助和意见!
【问题讨论】:
标签:
javascript
arrays
for-loop
【解决方案1】:
如果不需要,您可以通过检查类别和 continuethe 循环进行迭代,并使用计数器将所需产品计数到零并退出循环。
let count = 10;
for (const product of json) {
if (product.category !== 'X') continue;
renderProduct(product);
if (!--count) break;
}
【解决方案2】:
您需要在数组内部使用 check 并在循环外执行 renderProduct() 函数:
var json = [{id:1,category:'X'},{id:2,category:'X'},{id:3,category:'Y'}...]; // this array contain list of your items
var topTen = [];
for(let i=0;i<json.length;i++)
{
let product = json[i]
let category = product.category
if(category == 'X' && topTen.length <= 9){
topTen.push(product);
}
if(topTen.length >= 10){
break;
}
}
console.log('first 10 items by category: ', topTen);
renderProduct() //this is a function that prints the product to the DOM
检查这个例子HERE
祝你好运