文章目录
前言
ES6中提供了Set数据容器,这是一个能够存储无重复值的有序列表。
一、创建Set
1.new +add
- 通过new Set()可以创建Set
- 通过add方法能够向Set中添加数据项
//Set
let set= new Set();
set.add(1);
set.add('1');
console.log(set.size);//2
2.数组(具有迭代器的对象)构造
let set = new Set([1,2,3,3,3,3]);
console.log(set.size);//3
注意:Set构造器会确保不会存在重复的数据项
拓展:Set和数组的转换
1.数组转换成Set
将数组传入Set构造器
let set = new Set([1,2,3,3,3,3]);
2.Set转换成数组
使用扩展运算符。扩展运算符能将数组中的数据项切分开,作为独立项传入到函数,如果将扩展运算符用于可迭代对象的话,就可以将可迭代对象转换成数组
let [...arr]=set;
console.log(arr); // [1,2,3]
二、常用方法
1.has()
可以使用has()方法来判断某个值是否存在于Set中
let set = new Set([1,2,3,3,3,3]);
console.log(set.has(5)); //false
2.delete()
使用delete()方法从Set中删除某个值,或者使用clear()方法从Set中删除所有值:
let set = new Set([1,2,3,3,3,3]);
console.log(set.size);//3
console.log(set.has(5)); //false
set.delete(1);
console.log(set.has(1)); //false
console.log(set.size); //2
3.forEach()
可以使用forEach方法来遍历Set中的数据项,该方法传入一个回调函数callback,还可以传入一个this,用于回调函数之中:回调函数callback中有三个参数:
- 元素值;(value)
- 元素索引;(key)
- 将要遍历的对象;
Set中的value和key是相同的,这是为了让Set的forEach方法和数组以及Map的forEach方法保持一致,都具有三个参数。
let set = new Set([1,2,3,3,3,3]);
set.forEach(function (value,key,ownerSet) {
console.log(value);
console.log(key);
})
let set = new Set([1,2,3,3,3,3]);
let operation ={
print(value){
console.log(value);
},
iterate(set=[]){
set.forEach(function(value,key,ownerSet){
this.print(value);
this.print(key);
},this);
}
}
operation.iterate(set);
输出:1 1 2 2 3 3
如果回调函数使用箭头函数的话,就可以省略this的入参,这是因为箭头函数会通过作用域链找到当前this对象
let set = new Set([1,2,3,3,3,3]);
let operation ={
print(value){
console.log(value);
},
iterate(set=[]){
set.forEach((value,key)=>{
this.print(value);
this.print(key);
})
}
}
operation.iterate(set);
拓展:function函数和箭头函数区别
1.定义函数的书写方式
//function定义函数
function aaa(a,b){
return a+b;
}
//箭头函数定义函数
var aaa=(a,b)=>{return a+b;}
2.this指向
function传统定义的函数,this指向随着调用环境的改变而改变,而箭头 函数中的指向则是固定不变,一直指向定义环境的。
///function定义函数中的this指向
function aaa(){
console.log(this)
}
var obj={
aaa:aaa
};
aaa();//此时输出window对象
obj.aaa();//此时输出obj对象
///箭头函数中的this指向
var aaa=()=>{
console.log(this)
};
var obj={
aaa:aaa
}
aaa();//此时指向window
obj.aaa();//此时指向window
3.构造函数
箭头函数固然好用,但是不能用于构造函数,即不能被new一下;
///使用function方法定义构造函数
function per(){
this.name='aaa';
this.sex='man'
};
var ming=new per();
console.log(ming); /// {name: "aaa", sex: "man"}
///使用箭头函数定义构造函数
var per=>{
this.name='bbb';
this.sex='women';
};
var gang=new per();
///运行便会报错:Uncaught TypeError: per is not a constructor
4.变量提升
由于js的内存机制,function的级别最高,而用箭头函数定义函数的时候,需要var(let const定义的时候更不必说)关键词,而var所定义的变量不能得到变量提升,故箭头函数一定要定义于调用之前
///function定义函数时候的位置
aaa();//aaa
function aaa(){
console.log('aaa')
}
///箭头函数定义的位置
var aaa=()=>{
console.log('aaa')
};
aaa();//aaa
bbb();///报错bbb is not a function
var bbb=()=>{
console.log('bbb')
}