繁花如伊
正如Maheer Ali所说的,您可以使用Array#findIndex,但是它将返回一个值-满足条件的第一个值。在您的示例中,如果您有许多correct键等于的对象true,您仍将获得其中之一。因此,如果您希望所有对象都满足要求,则有许多解决方案。Array#reduce正如Maheer Ali在评论中建议的那样,您可以尝试使用Array#reduce。更短,并且在数组上具有唯一的循环:const arr = [ {correct: false}, {correct: true}, {correct: false}, {correct: true}, ], filtered = arr.reduce((acc, item, index) => ((item.correct) ? [...acc, index] : acc), []);console.log(`the correct answers are ${filtered.join(', ')}`);Array#map 和 Array#filter尝试Array#map(Array#filter用于删除false值):const arr = [ {correct: false}, {correct: true}, {correct: false}, {correct: true}, ], filtered = arr.map((item, index) => ((item.correct) ? index : false)).filter((item) => (item));console.log(`the correct answers are ${filtered.join(', ')}`);但是,该数组将循环两次(一次是Array#map,另一次是Array#filter。)。for...in 陈述最终,您可以通过循环遍历原始索引,将索引推入一个空数组中,以实现此目的for...in:const arr = [ {correct: false}, {correct: true}, {correct: false}, {correct: true}, ], filtered = []; for (let index in arr) { if (arr[index].correct) { filtered.push(index); }}console.log(`the correct answers are ${filtered.join(', ')}`);