简体   繁体   English

如何使用 splice 方法删除数组

[英]How to remove array using splice method

I've created (3) lists.我已经创建了 (3) 个列表。 What I'm trying to do:我正在尝试做的事情:

-When the checkbox is checked, push values into the mainArray (which I've gotten to work) - 当复选框被选中时,将值推入 mainArray(我已经开始工作)

-When the checkbox unchecked, remove values from the mainArray. - 当复选框未选中时,从 mainArray 中删除值。

For example: If input A is unchecked, remove [6, 7, 8, 9, 10] from the mainArray.例如:如果输入 A 未选中,则从 mainArray 中删除 [6, 7, 8, 9, 10]。

Any help or input here would be greatly appreciated!任何帮助或输入在这里将不胜感激! Cheers.干杯。

 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 if (!a.checked) { let index = mainArray.indexOf(list) if (index != -1) { mainArray.splice(index) console.log(mainArray) } } }); b.addEventListener('change', function(e) { if (b.checked) { mainArray.push(list2) console.log(mainArray) } else if (!b.checked) { let index = mainArray.indexOf(list2) if (index != -1) { mainArray.splice(index) console.log(mainArray) } } }) c.addEventListener('change', function(e) { if (c.checked) { mainArray.push(list3) console.log(mainArray) } else if (!c.checked) { let index = mainArray.indexOf(list3) if (index != -1) { list3.splice(index) console.log(mainArray) } } })
 <input class="input-1" type="checkbox" value = "a"> A <input class="input-2" type="checkbox" value = "b"> B <input class="input-3" type="checkbox" value = "c"> C

Any help, or input here would be appreciated.任何帮助或输入在这里将不胜感激。

Quick and dirty way to accomplish the same thing.快速而肮脏的方式来完成同样的事情。 Each time you click a checkbox, it recalculates mainArray from scratch, using the currently selected checkboxes and their data-list attributes to build it.每次单击复选框时,它mainArray从头开始重新计算mainArray ,使用当前选定的复选框及其data-list属性来构建它。

 [...document.querySelectorAll(".listy")].forEach(input => { input.addEventListener('change', (e) => { const mainArray = [...document.querySelectorAll(".listy:checked")].flatMap(el => JSON.parse(el.dataset.list)); console.log(mainArray); }); });
 <input class="listy" type="checkbox" value = "a" data-list="[1,2,3,4,5]"> A <input class="listy" type="checkbox" value = "b" data-list="[6,7,8,9,10]"> B <input class="listy" type="checkbox" value = "c" data-list="[11,12,13,14,15]"> C

You need to delete only one, so make sure you pass the second param.您只需要删除一个,因此请确保传递第二个参数。

mainArray.splice(index, 1);

You can also make this more generic by accessing a list at the index of the letter eg a = 0, b = 1, c = 2, etc... by normalizing the character codes into an index.您还可以通过访问字母索引处的列表(例如 a = 0、b = 1、c = 2 等)来使其更通用,方法是将字符代码规范化为索引。

Full example完整示例

 const mainArray = []; const lists = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15] ]; const handleClick = (e) => { const input = e.target; const listIndex = input.value.charCodeAt(0) - 97; const foundList = lists[listIndex]; if (input.checked) { mainArray.push(foundList); } else { let index = mainArray.indexOf(foundList); if (index !== -1) { mainArray.splice(index, 1); } } console.log(JSON.stringify(mainArray)); }; document.querySelectorAll('.list') .forEach(el => el.addEventListener('input', handleClick));
 <input class="list" type="checkbox" value="a"> A <input class="list" type="checkbox" value="b"> B <input class="list" type="checkbox" value="c"> C

A better way to achieve this would be to make the mail list mutable and just replace the value.实现此目的的更好方法是使邮件列表可变并仅替换该值。 When updating the value, just look at the current selections and reduce the lists.更新值时,只需查看当前选择并减少列表。

 let mainList = []; // Make this mutable... const subLists = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15] ]; const syncChoices = (inputs, lists) => [...inputs].reduce((acc, { checked }, index) => checked ? [...acc, ...lists[index]] : acc, []); const handleClick = (e) => { mainList = syncChoices(document.querySelectorAll('.list'), subLists); // Set console.log(JSON.stringify(mainList)); // Print the list }; document.querySelectorAll('.list') .forEach(el => el.addEventListener('input', handleClick));
 .as-console-wrapper { max-height: 4em !important; }
 <input type="checkbox" class="list" data-index="0"> A <input type="checkbox" class="list" data-index="1"> B <input type="checkbox" class="list" data-index="2"> C

You should be referencing mainArray instead of list .您应该引用mainArray而不是list

 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 if (!a.checked) { let index = mainArray.indexOf(list) if (index != -1) { mainArray.splice(index) console.log(mainArray) } } }); b.addEventListener('change', function(e) { if (b.checked) { mainArray.push(list2) console.log(mainArray) } else if (!b.checked) { let index = mainArray.indexOf(list2) if (index != -1) { mainArray.splice(index) console.log(mainArray) } } }) c.addEventListener('change', function(e) { if (c.checked) { mainArray.push(list3) console.log(mainArray) } else if (!c.checked) { let index = mainArray.indexOf(list3) if (index != -1) { mainArray.splice(index) console.log(mainArray) } } })
 <input class="input-1" type="checkbox" value = "a"> A <input class="input-2" type="checkbox" value = "b"> B <input class="input-3" type="checkbox" value = "c"> C

Here is another way of doing the same:这是执行相同操作的另一种方法:

 const arr = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]], cbs=document.querySelectorAll("input[type=checkbox]") document.body.onchange=()=> console.log(arr.filter((_,i)=> cbs[i].checked).flat() );
 <label><input type="checkbox"> A</label> <label><input type="checkbox"> B</label> <label><input type="checkbox"> C</label>

In a real use case you will probably need to limit the selector document.body to the actual container surrounding the checkboxes.在实际用例中,您可能需要将选择器document.body限制为复选框周围的实际容器。

If you really, really want to do it with .splice() then maybe the following could be a way to do it:如果你真的,真的想用.splice()做到这一点,那么也许以下可能是一种方法:

 const arr = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]], cbs=document.querySelectorAll("input[type=checkbox]"); document.body.onchange=()=>{ for(var res=arr.slice(0),i=cbs.length;i--;) if(!cbs[i].checked) res.splice(i,1); console.log(res.flat()); };
 <label><input type="checkbox"> A</label> <label><input type="checkbox"> B</label> <label><input type="checkbox"> C</label>

In order to preserve the original array I create a shallow copy first with .slice(0) .为了保留原始数组,我首先使用.slice(0)创建了一个浅拷贝。 The for loop is then made to count down from the highest index to zero, splice ing away an element from the res -array whenever the associated cbs -element is not checked.然后使for循环从最高索引倒数到零,每当检查关联的cbs元素时,就会从res数组中splice掉一个元素。

Your logic is right but the way you're using arr.splice() is wrong.您的逻辑是正确的,但您使用 arr.splice() 的方式是错误的。

For it to work in your case you should give a second argument to splice to inform how many elements you wish to remove为了让它在您的情况下工作,您应该给 splice 提供第二个参数,以告知您希望删除多少个元素

Ex:前任:

 let arr = [1,2,3,4,5,6,7,8,9] arr.splice(3,10)

This will remove all elements starting from index 3 in the array.这将删除数组中从索引 3 开始的所有元素。

Since in your case you pre defined the number of elements in each array you wish to remove i believe using this method will be the simplest way.由于在您的情况下,您预先定义了要删除的每个数组中的元素数,因此我相信使用此方法将是最简单的方法。

There are also other ways to use splice() where you can select the exact element you wish to remove.还有其他使用 splice() 的方法,您可以在其中选择要删除的确切元素。

Here's the link, everything u need to know about splice will be here ,这是链接,您需要了解的有关拼接的所有信息都在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM