使用.filter或.map等方法返回数组中值为'bad'的元素索引
获取数组中"bad"元素的索引
给定数组:
let class_required = new Array("bad", "bad", "good", "bad", "good", "bad", "bad", "bad", "good");
要提取值为"bad"的元素对应的索引,可以用以下几种数组方法实现:
方法1:map + filter
先通过map生成包含所有元素索引的数组,再用filter筛选出原数组对应位置值为"bad"的索引:
const badIndices = class_required .map((_, index) => index) .filter(index => class_required[index] === "bad"); console.log(badIndices); // 输出: [0, 1, 3, 5, 6, 7]
方法2:reduce
用reduce遍历一次数组,直接收集符合条件的索引,性能更优:
const badIndices = class_required.reduce((acc, value, index) => { if (value === "bad") acc.push(index); return acc; }, []); console.log(badIndices); // 输出: [0, 1, 3, 5, 6, 7]
说明
- 方法1逻辑直观,但会遍历数组两次;方法2仅遍历一次,在数组较大时效率更高。
内容的提问来源于stack exchange,提问作者user7212232
相关产品推荐
相关产品推荐

