gpt4 book ai didi

javascript - 使用 forEach 删除数组中的重复项

转载 作者:行者123 更新时间:2023-11-28 11:20:27 24 4
gpt4 key购买 nike

美好的一天,我正在尝试使用 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/

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