首页 > 解决方案 > 哪一个更好地使用 JavaScript 中的 new Set()?

问题描述

const array = [1, 2, 2, 2, 3, 4, 4, 4, 4, 5]

// first case
const filteredArray1 = new Set([...array])
 
// second case
const filteredArray2 = [...new Set(array)]

console.log(filteredArray1, filteredArray2)

标签: javascript

解决方案


const filteredArray2 = [...new Set(array)]

console.log(filteredArray1, filteredArray2)

// This is  much suitable way of doing it since you'll be directly getting the type of the new variable as an array. In the first method you have the chance of getting the type as a set or an object. 

推荐阅读