电脑桌面
添加蚂蚁七词文库到电脑桌面
安装后可以在桌面快捷访问

js中数组如何去重

来源:用友作者:用友2025-08-162

js中数组如何去重

在JavaScript中,你可以使用不同的方法来对数组进行去重。以下是一些常见的方法:

  1. 使用Set对象Set是一种集合数据结构,它只允许存储唯一的值,因此可以用来快速去重一个数组。

javascriptCopy code

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = [...new Set(arrayWithDuplicates)]; console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

  1. 使用filter()方法:使用filter()方法和indexOf()来创建一个新数组,其中只包含原数组中第一次出现的每个元素。

javascriptCopy code

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = arrayWithDuplicates.filter((value, index, self) => self.indexOf(value) === index); console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

  1. 使用reduce()方法:使用reduce()方法遍历数组,将每个元素添加到结果数组中,但只有当元素在结果数组中还未出现时才添加。

javascriptCopy code

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = arrayWithDuplicates.reduce((accumulator, currentValue) => {  if (!accumulator.includes(currentV

js中数组如何去重

在JavaScript中,你可以使用不同的方法来对数组进行去重。以下是一些常见的方法:使用Set对象:Set是一种集合数据结构,它只允许存储唯一的...
点击下载文档文档为doc格式

声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。如若本站内容侵犯了原著者的合法权益,可联系本站删除。

已经是第一篇
确认删除?
回到顶部
客服QQ
  • 客服QQ点击这里给我发消息
QQ群
  • 答案:my7c点击这里加入QQ群
支持邮箱
微信
  • 微信