JavaScript中如何按指定索引过滤多维数组?求正确实现
解决JavaScript移除多维数组(或对象)指定索引元素的问题
首先要纠正一个语法问题:你写的[0: ['example', 'example'], 1: ['example1', 'example1'], 2: ['example2', 'example2']]不是合法的数组字面量,数组不能用键值对形式定义元素,这其实是对象的写法。下面分两种情况给你解决方案:
情况一:你的array1确实是数组(正确格式)
如果array1是标准数组,正确写法是:
const array1 = [['example', 'example'], ['example1', 'example1'], ['example2', 'example2']];
此时你想移除索引0和2的元素,原代码从后往前遍历splice的逻辑其实是正确的,但你说得到相反结果,大概率是搞反了「移除」和「保留」的逻辑(比如误把keys当成要保留的索引),或者keys数组的实际值和你描述的不符。
更稳妥且易读的方式是用filter方法,直接生成新数组保留不需要移除的元素:
const array1 = [['example', 'example'], ['example1', 'example1'], ['example2', 'example2']]; const keysToRemove = [0, 2]; const filteredArray = array1.filter((_, index) => !keysToRemove.includes(index)); console.log(filteredArray); // 输出:[ ['example1', 'example1'] ]
这种方法不会修改原数组,避免了splice可能带来的索引偏移问题(虽然你从后往前遍历已经规避了这个问题)。
情况二:你的array1其实是对象(你写的键值对形式)
如果array1实际是一个以数字为键的对象,那数组的splice方法完全无效,需要用delete操作符删除指定键:
const obj1 = { 0: ['example', 'example'], 1: ['example1', 'example1'], 2: ['example2', 'example2'] }; const keysToRemove = [0, 2]; keysToRemove.forEach(key => delete obj1[key]); console.log(obj1); // 输出:{ 1: ['example1', 'example1'] }
原代码问题分析
如果你的array1是标准数组,原代码for (let i = keys.length -1; i >= 0; i--) array1.splice(Number(keys[i]),1);应该能得到正确结果——先删索引2,数组变成[['example', 'example'], ['example1', 'example1']],再删索引0,最后剩下[['example1', 'example1']]。如果得到相反结果,建议检查:
keys数组的实际值是否是[0,2],有没有写成[1]或者其他值- 是否把「移除索引」搞成了「保留索引」
内容的提问来源于stack exchange,提问作者dusteer marts
相关产品推荐
相关产品推荐

