本文共 1159 字,大约阅读时间需要 3 分钟。
Let’s say you have an array containing a series of primitive values, for example numbers or strings.
假设您有一个包含一系列原始值的数组,例如数字或字符串。
Some of those elements are repeated.
这些元素中有一些是重复的。
Like in this example:
像这个例子一样:
const list = [1, 2, 3, 4, 4, 3]
We can generare a new array containing the same values, without the duplicates, in this way:
我们可以通过这种方式生成一个包含相同值但没有重复值的新数组:
const uniqueList = [...new Set(list)]
uniqueList
will now be a new array with the values [1, 2, 3, 4]
in it.
现在, uniqueList
将是一个新数组,其中包含[1, 2, 3, 4]
值。
How does this work?
这是如何运作的?
Set
is a new data structure, introduced in ES6 in 2015, and its main characteristic is to be a container for data that can’t be repeated in the same set. .
Set
是一种新的数据结构,于2015年在ES6中引入,其主要特征是成为无法在同一集合中重复的数据的容器。 。
By initializing a Set with a destructured array (see the ...
operator before new Set()
), we pass values and Set automatically removes the duplicates. Then we convert it to an array by wrapping it into square brackets []
.
通过使用解构数组初始化Set(请参阅new Set()
之前的...
运算符),我们传递值,并且Set自动删除重复项。 然后,通过将其包装在方括号[]
,将其转换为数组。
This method works with anything that’s not an object: , , booleans, .
此方法适用于所有非对象: , ,布尔值, 。
翻译自:
转载地址:http://ihmgb.baihongyu.com/