在ES6之前,js仅提供了对数组的支持。ES6 中引入了4种新的数据结构,分别是Set(集合),Map(映射),WeakSet(弱集合),WeakMap(弱映射)。
一、Set
(1)概述:Set对象是值得集合,可以按照插入的顺序迭代它的顺序。Set中的元素只会出现一次,元素是唯一的。
用法:new Set([ iter ]);
参数iter是一个可迭代的对象,它的所有元素将被添加到新的Set中
在 Set 中,NaN 和 undefined 是可以被存储在 Set 中的,因为 NaN 在ES6中是严格相等的
new Set([+0,-0,NaN,2,3,5,5,undefined])
// 0 , NaN, 2 ,3 ,5 ,undefined
(2) size(length)属性
var st1 = new Set([NaN,NaN,2,3,5,5])
console.log(st1) // {NaN,2,3,4}
console.log(st1.size) // 4
3、方法
(1) 在 Set 对象尾部添加一个元素:Set.prototype.add(value)
var st2 = new Set([NaN,NaN,1,2,5,5])
st2.add(6)
st2.add(7).add("8")
console.log(st2)
// Set(6) {NaN, 1, 2, 5, 6, 7, "8"}
(2) 清除 Set 中所有的元素:Set.prototype.clear()
var st2 = new Set([NaN,NaN,1,2,5,5])
st2.clear()
console.log(st2)
//Set(0){}
(3) 判断值是否存在于 Set 中:Set.prototype.has(value)
var st2 = new Set([NaN,NaN,1,2,5,5])
console.log(st2.has(5)) // true
console.log(st2.has('1')) // false
console.log(st2.has(NaN)) // true
(4) 删除 Set 中的某个值: Set.prototype.delete(value);
var st2 = new Set([NaN,NaN,1,2,5,5])
st2.delete(2) //删除2
console.log(st2) // Set(3){NaN,1,5}
(5) 遍历 Set 对象中的元素:forEach()、keys()、values()、entries()
forEach:
function logElemt(val