2 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
也許這對(duì)你有幫助(我不知道我是否理解得很好)。
但是使用filter您可以獲取具有一個(gè)屬性的值(您可以匹配您想要的任何內(nèi)容)并且使用slice您將獲得前 N 個(gè)值。
因此,您不必迭代整個(gè)列表,而可以僅檢查這些值。
另外,如果您只想要匹配某個(gè)條件的元素?cái)?shù)量,則只需要使用filter和 length 。
var array = [
{
"username": "1",
"active": true
},
{
"username": "2",
"active": false
},
{
"username": "3",
"active": true
}
]
var total = 1 // total documents you want
var newArray = array.filter(e => e.active).slice(0, total);
console.log(newArray)
//To know the length of elements that match the condition:
var length = array.filter(e => e.active).length
console.log(length)

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
看看下面的代碼是否有幫助
function processLongArray() {
var myLongArray = [{
"username": "active"
}, {
"username": "active"
}, {
"username": "inactive"
}]; // and many more elements in the array
var count = 0;
var targetCount = 1; // stop after this number of objects
for (var i = 0; i < myLongArray.length; i++) {
var arrayItem = myLongArray[i];
// condition to test if the arrayItem is considered in count
// If no condition needed, we can directly increment the count
if (arrayItem.username === "active") {
count++;
}
if (count >= targetCount) {
console.log("OK we are done! @ " + count);
return count; // or any other desired value
}
}
}
processLongArray();
添加回答
舉報(bào)