【发布时间】:2016-04-13 04:54:08
【问题描述】:
请看下面的脚本。我正在用 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]}
- 为什么在
items.has([5,6,7,8])返回 false? - 为什么允许重复值?我认为“一个集合位于不能包含重复值的有序值列表中”
- 如何访问
items.add([5,6,7,8])添加的数组?
【问题讨论】:
-
[5, 6, 7, 8] !== [5, 6, 7, 8]这个代码也返回false,每个数组都是一个单独的对象。 -
“我认为一个集合在一个有序的值列表中” 列表是按定义排序的。集合通常不是。