美好的一天,我试图使用forEach循环从数组中删除重复元素.但是在这个时候我得到了一些错误.以下是我的代码
function removeDup(arr) {
let result = arr.forEach((item, index) => { if (index > 1) item.shift() });
return result;
}
Run Code Online (Sandbox Code Playgroud)
我甚至不确定这段代码是否适用于删除重复项,因为当我在浏览器中运行它时console会出现此错误
if(index> 1)item.shift(); ^
TypeError:item.push不是函数
首先,我如何修复此错误,其次此代码是否可以删除重复项?
你可以试试 :
function removeDup(arr) {
let result = []
arr.forEach((item, index) => { if (arr.indexOf(item) == index) result.push(item) });
return result;
}
Run Code Online (Sandbox Code Playgroud)
Explanaton:
首先用空数组初始化结果.然后遍历传递的数组,检查索引是否是第一次出现的项.推送到结果数组.返回结果数组.
替代方案:
function removeDup(arr) {
let result = []
arr.forEach((item, index) => { if (result.indexOf(item) === -1) result.push(item) });
return result;
}
Run Code Online (Sandbox Code Playgroud)
说明:
您可以通过检查该元素是否已被推入结果数组来避免将索引检查为首次出现.