gpt4 book ai didi

javascript - [...new set(array)] 在 JavaScript 中如何工作?

转载 作者:行者123 更新时间:2023-12-01 23:47:49 24 4
gpt4 key购买 nike

考虑:

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = [...new Set(ages)]

console.log(uniqueAges) // [26,27,28,29,30]

我知道 spread syntax .我搜索了有关set 的内容,但没有找到有关其工作原理的解释。

如何设置项目的比较并找到相似的项目?

如果设置,则在比较中使用循环。

最佳答案

Set 只能包含唯一值;这是根据 MDN 构成的等值:

Because each value in the Set has to be unique, the value equality will be checked. In an earlier version of ECMAScript specification, this was not based on the same algorithm as the one used in the === operator. Specifically, for Sets, +0 (which is strictly equal to -0) and -0 were different values. However, this was changed in the ECMAScript 2015 specification. See "Key equality for -0 and 0" in the browser compatibility table for details.

NaN and undefined can also be stored in a Set. All NaN values are equated (i.e. NaN is considered the same as NaN, even though NaN !== NaN).

Set 的创建中有一个隐式循环,使用 iterable interface传递的数组。 ... 中还有一个循环,它解压一个可迭代对象。

但是,检查一个元素是否已经在 Set 中不是使用循环来完成的 - 出于所有意图和目的,您可以将 Set 视为一个只有字典的字典键,没有值。代码几乎相同:

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]

const temp = {};
for (const age of ages) {
temp[age] = true;
}

const uniqueAges = [];
for (const age in temp) {
uniqueAges.push(age);
}

console.log(uniqueAges);

我故意写这种“低技术”的方式来说明正在发生的事情;请注意,对象键始终是字符串,因此结果将被字符串化。使用 Map 或将年龄存储为 values 会使它在效果上与 OP 的代码更加相似,但为了说明起见,我想保持简单。

关于javascript - [...new set(array)] 在 JavaScript 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63928416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com