gpt4 book ai didi

javascript - ES6 Set 允许重复数组/对象

转载 作者:数据小太阳 更新时间:2023-10-29 04:29:46 25 4
gpt4 key购买 nike

请看下面的脚本。我正在使用 Chrome 对其进行测试。

/*declare a new set*/
var items = new Set()

/*add an array by declaring as array type*/
var arr = [1,2,3,4];
items.add(arr);

/*print items*/
console.log(items); // Set {[1, 2, 3, 4]}

/*add an array directly as argument*/
items.add([5,6,7,8]);

/*print items*/
console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8]}

/*print type of items stored in Set*/
for (let item of items) console.log(typeof item); //object, object

/*check if item has array we declared as array type*/
console.log(items.has(arr)); // true

/*Now, check if item has array we added through arguments*/
console.log(items.has([5,6,7,8])); //false

/*Now, add same array again via argument*/
items.add([1,2,3,4]);

/*Set has duplicate items*/
console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]}
  1. 为什么在 items.has([5,6,7,8]) 返回 false?
  2. 为什么允许重复值?我认为“一个集合在一个有序的值列表中,不能包含重复值”
  3. 如何访问items.add([5,6,7,8])添加的数组?

最佳答案

  1. 为什么在 items.has([5,6,7,8]) 处返回 false?

    来自 MDN

    The Set object lets you store unique values of any type, whether primitive values or object references.

    使用引用而不是值来比较对象。集使用 SameValueZero(x, y)比较算法来比较值。如果 x 和 y 是相同的对象值,它表示返回 true。否则,返回 false

  2. 为什么允许重复值?我认为“一个集合在一个有序的值列表中,不能包含重复项”

    与#1 相同。如果集合中已经添加了相同对象(不只是外观相同),则称该非原始值已存在于集合中。

  3. 如何访问items.add([5,6,7,8])添加的数组?

    您必须创建一个变量并将该变量添加到集合中。然后这个变量可以用来检查集合是否有那个数组。

关于javascript - ES6 Set 允许重复数组/对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36588890/

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