使用 .findIndex 将满足条件的其他数组元素的所有索引保存到新数组中

Saving into new array all indexes of other array elements which meet condition using .findIndex

const jumbledNums = [123, 7, 25, 78, 5, 9]; 

const lessThanTen = jumbledNums.findIndex(num => {
  return num < 10;
});

你好, 我的问题是这个片段只返回元素满足条件 num < 10 的第一个满足索引,但我想将所有满足条件的索引保存到新数组中。根据我在 .findIndex() 的 Mozilla 文档中阅读的内容,它在找到满足条件的元素后不会检查其他元素。有什么方法可以对数组中的每个元素重复 .findIndex(例如使用 .map()),或者我需要使用另一种方法来做到这一点?

您可以先映射小于 10 的索引,或者 -1 然后过滤索引数组以获得有效索引。

const
    jumbledNums = [123, 7, 25, 78, 5, 9],
    lessThanTen = jumbledNums
        .map((v, i) => v < 10 ? i : -1)
        .filter(i => i !== -1);

console.log(lessThanTen);

您可以使用 array.filter,这将 return 一个检查条件的新数组。获取值

但是array.filter没有return索引,所以你可以使用array.map,这将创建一个新数组,你可以使用array.filter删除未定义的案例。

希望这能解决问题。

const jumbledNums = [123, 7, 25, 78, 5, 9]; 

const lessThan10 = jumbledNums.filter(o => o<10)

console.log("array with less than 10", lessThan10)

const lessThan10Indexes = jumbledNums.map((o,i) =>{ 
  return o < 10 ? i : undefined
}).filter(o => o)

console.log("array with less than 10 Indexes", lessThan10Indexes)

使用Array#reduce()

const jumbledNums = [123, 7, 25, 78, 5, 9];

const lessThanTen = jumbledNums.reduce((a, c, i) => (c < 10 ? a.concat(i) : a), [])

console.log(lessThanTen)