gpt4 book ai didi

javascript - 单击按钮时删除数组项

转载 作者:行者123 更新时间:2023-12-04 10:09:10 25 4
gpt4 key购买 nike

如何在点击时删除项目?这是我目前拥有的:

function deleteUser(name) {
var person = name;

const array = ['John','Mark','Andy'];
const index = array.indexOf(person);
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
}
<button onclick="deleteUser('John')"> Delete User </button>
<button onclick="deleteUser('Mark')"> Delete User </button>
<button onclick="deleteUser('Andy')"> Delete User </button>


我已经可以删除数组上的值,但我得到了不同的结果。
前任。当我删除一个值 John .我收到 ['Mark','Andy']但是当我删除 Mark我收到 ['John','Andy'] .

我想在单击时删除阵列上的项目

最佳答案

也许你可以定义 array在函数之外并使用 .filter() 删除项目。重要的是.filter()创建一个新数组,因此您需要在函数中重新分配结果。从文档中看到:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.



尝试如下:

let array = ['John','Mark','Andy'];

const deleteUser = name => {
array = array.filter(e => e !== name);
console.log(array);
}
<button onclick="deleteUser('John')"> Delete User </button>
<button onclick="deleteUser('Mark')"> Delete User </button>
<button onclick="deleteUser('Andy')"> Delete User </button>


我希望这有帮助!

关于javascript - 单击按钮时删除数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61409523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com