javascript 代码中展开运算符的作用是什么?

What is the role of the spread operator in this javascript code?

今天在medium看了this article,下面的spread operator我不是很懂

我知道展开运算符用于接收数组作为函数中的参数。在上面的代码中,展开运算符是做什么的?将对象转换为数组?

展开运算符结合数组语法 ([]) 从 Set 中获取值,由于缺少更好的术语,将它们展开,因此您得到一个包含所有值的数组集。最终结果是您将一个数组转换为另一个包含原始数组中唯一值的数组。

I know that the spread operator is used to receive array as a parameter in a function

在这种情况下,三个点 ... 被称为 rest parameters syntax, not spread syntax. In the code included in your question, the context in which three dots ... are used, it is known as spread syntax

In the code above, what does the spread operator do?

它遍历 Set 展开 (将 Set 中的条目添加到新数组

以下代码片段显示了一个简单示例:

const set = new Set([1,2,3]);
const newArr = [...set];

console.log(newArr);

让我们一行一行地看。

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]

这将创建一个包含一些数字列表的数组 entries

现在,当我们这样做时,new Set(entries),我们从 entries 数组创建了一个 SetSet 是您可能已经知道的不同元素的集合。

因此,new Set(entries)entries 给我们一个 Set 如下: Set(8) {1, 2, 3, 4, 5, …}

现在,... 运算符将 Set 中的不同元素展开以创建一个数组,即行 - var unique_entries = [...new Set(entries)]