如何使用JavaScript查找数组中包含特定值的所有索引
问题根因
你使用的findIndex()方法本身设计就是仅返回第一个匹配条件的元素索引,匹配到第一个符合要求的元素后就会终止遍历,所以只能拿到第一个2021对应的下标3,无法返回所有匹配结果。
解决代码
下面提供两种常用的实现方案:
方案1:reduce实现(简洁高效,一行完成逻辑)
function test() { const dates = [ 'October 31, 2020', 'November 30, 2020', 'December 31, 2020', 'January 31, 2021', 'February 28, 2021', 'March 31, 2021', ]; // 遍历数组,符合条件就把当前索引存入结果数组 const indexes = dates.reduce((result, item, index) => { if (item.includes('2021')) result.push(index); return result; }, []); console.log(indexes); // 输出结果:[3, 4, 5] }
方案2:forEach遍历实现(逻辑直观,适合新手理解)
function test() { const dates = [ 'October 31, 2020', 'November 30, 2020', 'December 31, 2020', 'January 31, 2021', 'February 28, 2021', 'March 31, 2021', ]; const indexes = []; dates.forEach((item, index) => { if (item.includes('2021')) { indexes.push(index); } }) console.log(indexes); // 输出结果:[3, 4, 5] }
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

