如何使用splice方法移除主数组中对应取消勾选的子数组
错误修复
你代码存在两处逻辑错误,修改后即可正常运行:
splice方法需要传入第二个参数指定删除的元素数量,仅传起始索引会删除从该位置到数组末尾的所有元素,需要补充参数1表示仅删除匹配到的单个元素- 第三个复选框的取消勾选逻辑错误操作了原数组
list3,应该操作存储数据的mainArray
修正后JS代码
const a = document.querySelector('.input-1') const b = document.querySelector('.input-2') const c = document.querySelector('.input-3') const list = [1, 2, 3, 4, 5]; const list2 = [6, 7, 8, 9, 10]; const list3 = [11, 12, 13, 14, 15]; const mainArray = []; a.addEventListener('change', function(e) { if (a.checked) { mainArray.push(list) console.log(mainArray) } else { let index = mainArray.indexOf(list) if (index != -1) { // 补充第二个参数1,仅删除当前匹配元素 mainArray.splice(index, 1) console.log(mainArray) } } }); b.addEventListener('change', function(e) { if (b.checked) { mainArray.push(list2) console.log(mainArray) } else { let index = mainArray.indexOf(list2) if (index != -1) { mainArray.splice(index, 1) console.log(mainArray) } } }) c.addEventListener('change', function(e) { if (c.checked) { mainArray.push(list3) console.log(mainArray) } else { let index = mainArray.indexOf(list3) if (index != -1) { // 修正操作对象为mainArray,同时补充删除数量参数 mainArray.splice(index, 1) console.log(mainArray) } } })
优化建议(可选)
你可以把重复逻辑封装成通用函数,减少冗余代码,后续新增复选框也不用重复写监听逻辑:
const config = [ { selector: '.input-1', data: [1, 2, 3, 4, 5] }, { selector: '.input-2', data: [6, 7, 8, 9, 10] }, { selector: '.input-3', data: [11, 12, 13, 14, 15] } ] const mainArray = [] config.forEach(item => { const el = document.querySelector(item.selector) el.addEventListener('change', () => { if (el.checked) { mainArray.push(item.data) } else { const index = mainArray.indexOf(item.data) index !== -1 && mainArray.splice(index, 1) } console.log(mainArray) }) })
内容的提问来源于stack exchange,提问作者WeeklyButterfly34
相关产品推荐
相关产品推荐

