文章目录
Set([iterable])
本身是一个构造函数,用来生成Set数据结构。它可以存储任何类型的唯一值,无论是原始值或者是对象引用。
- Set结构不会添加重复的值。而且Set内部判断两个值是否不同,使用的算法和Object.is(v1,v2)的方法相同,类似于===,但是NaN等于自身。
- Set函数可使用iterator结构的对象作为参数来进行初始化
function outputSet(set){
for(let v of set){
console.log(v);
}
}
var s = new Set();
var arr = [1,23,4,5,6,4,3];
arr.map(a => s.add(a));
outputSet(s);
/*Output
1
23
4
5
6
3
*/
var initSet = new Set(arr);
outputSet(initSet);
/*Output
1
23
4
5
6
3
*/
利用其不会添加重复值的特点,去除重复值
var arr = [1,2,3,4,2,1,3,5,4,6,NaN,NaN];
arr = [...new Set(arr)];
console.log(arr);
//Output: [1, 2, 3, 4, 5, 6, NaN]
属性
Set.length
值为0
get Set[@@species]
构造函数用来创建派生对象
Set.prototype
表示Set构造器的原型,允许先所有Set对象添加新的属性。
实例
以下列代码为例
function outputSet(set){
for(let v of set){
console.log(v);
}
}
var arr = [1,2,4,5,2,5,4,3,5,4];
var expSet = new Set(arr);
属性
Set.prototype.constructor
返回实例的构造函数。默认情况下是Set()。
expSet.__proto__.constructor;
//result: ƒ Set() { [native code] }
Set.prototype.size
返回Set对象的值的个数
expSet.size
//result: 5
方法
Set.prototype.add(value)
在Set对象尾部添加一个元素。返回该Set对象
expSet.add("val");
outputSet(expSet);
/*Output:
1
2
4
5
3
val
*/
Set.prototype.clear()
移除Set对象内的所有元素
Set.prototype.delete(value)
移除Set对象中与这个值相等的元素,返回和Set.prototype.has(value)
相同的结果。
- 如果Set对象中存在与这个值相等的元素