如何获取数组中符合特定条件的元素索引?JavaScript有findIndexAll()吗?
获取数组中符合条件元素的所有索引
首先明确:JavaScript 标准库中没有内置的findIndexAll()方法,不过我们可以通过几种简单的方式实现需求。
以下是针对你给出的示例数组,获取device='1'元素索引的几种方案:
方案1:使用reduce()(推荐)
reduce()可以在遍历数组的同时,逐步收集符合条件的索引,代码简洁高效:
const arr = [ { device: '1', type: 'a' }, { device: '2', type: 'b' }, { device: '3', type: 'c' }, { device: '1', type: 'd' } ]; const targetIndices = arr.reduce((acc, item, index) => { if (item.device === '1') { acc.push(index); } return acc; }, []); console.log(targetIndices); // 输出 [0, 3]
方案2:使用forEach()遍历
如果觉得reduce()不够直观,也可以用forEach()手动遍历并收集索引:
const arr = [ { device: '1', type: 'a' }, { device: '2', type: 'b' }, { device: '3', type: 'c' }, { device: '1', type: 'd' } ]; const targetIndices = []; arr.forEach((item, index) => { if (item.device === '1') { targetIndices.push(index); } }); console.log(targetIndices); // 输出 [0, 3]
方案3:封装自定义的findIndexAll方法
如果需要多次使用类似功能,可以自己封装一个方法,甚至挂载到数组原型上(注意:修改原型可能引发冲突,谨慎使用):
封装独立函数
function findIndexAll(arr, callback) { const indices = []; arr.forEach((item, index) => { if (callback(item, index, arr)) { indices.push(index); } }); return indices; } // 使用示例 const arr = [ { device: '1', type: 'a' }, { device: '2', type: 'b' }, { device: '3', type: 'c' }, { device: '1', type: 'd' } ]; const targetIndices = findIndexAll(arr, item => item.device === '1'); console.log(targetIndices); // 输出 [0, 3]
挂载到数组原型(谨慎使用)
// 注意:原型扩展可能与其他代码冲突,需谨慎 Array.prototype.findIndexAll = function(callback) { const indices = []; this.forEach((item, index) => { if (callback(item, index, this)) { indices.push(index); } }); return indices; }; // 使用示例 const arr = [ { device: '1', type: 'a' }, { device: '2', type: 'b' }, { device: '3', type: 'c' }, { device: '1', type: 'd' } ]; const targetIndices = arr.findIndexAll(item => item.device === '1'); console.log(targetIndices); // 输出 [0, 3]
内容的提问来源于stack exchange,提问作者Jibun no Kage
相关产品推荐
相关产品推荐

