gpt4 book ai didi

javascript - .splice() 从数组中移除 2 个对象而不是 1 个

转载 作者:行者123 更新时间:2023-12-02 07:20:50 27 4
gpt4 key购买 nike

例如,当输入“John Smith”时,slice 会删除前两个员工姓名,而不仅仅是 John 的姓名。知道为什么会这样吗?

let removeEmployee = '';
let employees = [
{
name: 'John Smith'
}, {
name: 'Jackie Jackson'
}, {
name: 'Chris Jones'
}, {
name: 'Amanda Cullen'
}, {
name: 'Jeremy Goodwin'
}, ]

removeEmployee = prompt('Enter the name of the employee to be removed:');

function employeeExists(employee) {
return employees.some(function(el) {
return el.name === employee;
});
}

if (employeeExists(removeEmployee)) {
employees.forEach(function(employee, index, object) {
if (employee.name === removeEmployee) {
object.splice(index, 1);
} else {
console.log(employee.name);
}
});
} else {
console.log('That employee does not exist, please try again.');
}

最佳答案

你可以使用 filter 而不是 forEach 让事情变得更简单:

if (employeeExists(removeEmployee)) {   
employees = employees.filter(e => e.name !== removeEmployee);
}

如果你仍然想使用splice,你可以使用findIndex:

let employees = [ {name: 'John Smith'}, {name: 'Jackie Jackson'}, {name: 'Chris Jones'}, {name: 'Amanda Cullen'}, {name: 'Jeremy Goodwin'} ];
var removeEmployee = 'Chris Jones';
var index = employees.findIndex(e => e.name === removeEmployee);
employees.splice(index, 1);
console.log(employees);

关于javascript - .splice() 从数组中移除 2 个对象而不是 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46500488/

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