如何在JavaScript中使用indexOf()查找所有匹配项的索引
查找数组中所有匹配项的索引方法
针对你给出的数组,这里提供几种实用的方法来获取所有匹配元素的索引:
方法一:利用indexOf()循环查找
indexOf()支持第二个参数指定起始搜索位置,我们可以通过循环不断更新起始位置,直到找不到匹配项为止:
const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"]; const target = "apple"; const indices = []; let currentIndex = fruits.indexOf(target); while (currentIndex !== -1) { indices.push(currentIndex); // 从当前索引的下一位开始继续搜索,避免重复匹配 currentIndex = fruits.indexOf(target, currentIndex + 1); } console.log(indices); // 输出 [0, 3, 5]
方法二:用forEach()遍历记录索引
直接遍历数组的每个元素,判断是否匹配目标值,匹配则记录对应的索引:
const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"]; const target = "apple"; const indices = []; fruits.forEach((fruit, index) => { if (fruit === target) { indices.push(index); } }); console.log(indices); // 输出 [0, 3, 5]
方法三:使用reduce()累积结果
通过reduce()方法遍历数组,将符合条件的索引累积到结果数组中:
const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"]; const target = "apple"; const indices = fruits.reduce((acc, fruit, index) => { if (fruit === target) { acc.push(index); } return acc; }, []); console.log(indices); // 输出 [0, 3, 5]
内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

