ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
let array = [1,2,3,4,5,5,5] console.log([new Set(array)]); //打印结果为set数据结构,如下图示
-
实现对数组的去重
console.log([...new Set(array)]); // [1, 2, 3, 4, 5],用扩展运算符可转换成数组
-
去字符串的去重
let str = 'abccdd' console.log([...new Set(str)]); //["a", "b", "c", "d"]console.log([...new Set(str)].join('')); //abcd,要用join连接成字符串
-
**Array.from**方法可以将 Set 结构转为数组。let array = [1,2,3,4,5,5,5] console.log(Array.from(new Set(array))); // [1, 2, 3, 4, 5]