Set
对象类型是在 ES6 中引入的,配合展开操作...
一起,我们可以使用它来创建一个新数组,该数组只有唯一的值。
const array = [1, 1, 2, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]
在 ES6 之前,隔离惟一值将涉及比这多得多的代码。
此技巧适用于包含基本类型的数组:undefined
,null
,boolean
,string
和number
。(如果你有一个包含对象,函数或其他数组的数组,你需要一个不同的方法!)