ES6集允许重复的数组/对象 [英] ES6 Set allows duplicate array/object

查看:488
本文介绍了ES6集允许重复的数组/对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下脚本.我正在用Chrome进行测试.

Please have a look at the below script. I am testing it with 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. Why it is returning false at items.has([5,6,7,8])?
  2. Why it is allowing duplicate values? I thought "A set is in an ordered list of values that cannot contain duplicates"
  3. How to access array added by items.add([5,6,7,8])?

推荐答案

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

  1. Why it is returning false at items.has([5,6,7,8])?

来自 MDN

通过Set对象,您可以存储任何类型的唯一,无论是原始值还是对象引用.

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

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

The objects are compared using the reference, not the value. Sets uses SameValueZero(x, y) comparison algorithm to compare values. It says Return true if x and y are the same Object value. Otherwise, return false.

为什么允许重复值?我以为集合在不能包含重复项的值的有序列表中"

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

Same as #1. An non-primitive value is said to be already exists in set if the same object(not just same looking) already added in the set.

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

How to access array added by items.add([5,6,7,8])?

您必须创建一个变量并将该变量添加到集合中.然后可以使用此变量检查set是否具有该数组.

You've to create a variable and add the variable to the set. Then this variable can be used to check if set has that array or not.

这篇关于ES6集允许重复的数组/对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆