美好的一天,我正在尝试使用 forEach
从数组中删除重复元素环形。但此时我遇到了一些错误。下面是我的代码
function removeDup(arr) {
let result = arr.forEach((item, index) => { if (index > 1) item.shift() });
return result;
}
我什至不确定此代码是否可以用于删除重复项,因为当我在浏览器中运行它时console
我收到此错误
if (index > 1) item.shift(); ^
TypeError: item.push is not a function
首先,我该如何修复这个错误,其次这个代码是否可以删除重复项?
最佳答案
你可以尝试:
function removeDup(arr) {
let result = []
arr.forEach((item, index) => { if (arr.indexOf(item) == index) result.push(item) });
return result;
}
说明:
首先用空数组初始化结果。然后遍历传递的数组,检查索引是否是其第一次出现的项目。插入结果数组。返回结果数组。
替代解决方案:
function removeDup(arr) {
let result = []
arr.forEach((item, index) => { if (result.indexOf(item) === -1) result.push(item) });
return result;
}
说明:
您可以通过检查该元素是否已被插入结果数组来避免检查索引是否第一次出现。
关于javascript - 使用 forEach 删除数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54757902/