Javascript过滤唯一值、简单的数组去重(ES6语法)

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 之前,隔离惟一值将涉及比这多得多的代码。

此技巧适用于包含基本类型的数组:undefinednullbooleanstringnumber。(如果你有一个包含对象,函数或其他数组的数组,你需要一个不同的方法!)

猜你喜欢

转载自blog.csdn.net/qq_42363090/article/details/108467689