可以使用Set数据结构来创建一个只包含唯一值的数组。Set是一种包含不同值的数据结构,可以轻松地将重复的项忽略掉。
以下是一个使用Set的示例代码:
const arr = [1, 2, 3, 4, 5, 5, 6, 6, 7];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5, 6, 7]
在上面的代码中,我们首先定义了一个包含重复值的数组arr。然后,我们创建了一个Set实例,将数组arr传递给Set构造函数。由于Set只包含唯一的值,因此它会自动去除重复项。最后,我们使用展开运算符将Set转换为数组,并将其分配给变量uniqueArr。最终,uniqueArr只包含唯一值。
另一种使用Set创建只包含唯一值的数组的方法是使用Array.from()函数:
const arr = [1, 2, 3, 4, 5, 5, 6, 6, 7];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3, 4, 5, 6, 7]
这个例子与前一个类似,但是使用了Array.from()函数从Set中创建数组。