ES6-Set和Map

Set

Set是一系列无序、没有重复值的数据集合

方法

1、add()添加成员

const s = new Set();
s.add(1).add(2).add(1);
console.log(s);

在这里插入图片描述不能添加重复的值
2、has()判断是否包含某个成员

const s = new Set();
s.add(1).add(2).add(1);
console.log(s.has(1));//true
console.log(s.has(3));//false

3、delete删除指定成员,clear()删除所有成员

const s = new Set();
s.add(1).add(2).add(1);
s.delete(1)
console.log(s);//Set(1) { 2 }

4、forEach遍历成员,按照成员添加进集合的顺序遍历

const s = new Set();
s.add(1).add(2).add(3);
s.forEach(function(value){
    
    
	console.log(value);
});

在这里插入图片描述

Set构造函数的参数

1、数组

const s = new Set([1,2,3]);
console.log(s);
//Set(3) { 1, 2, 3 }

2、字符串

const s = new Set('hello');
console.log(s);//Set(4) { 'h', 'e', 'l', 'o' }

3、arguments

function func() {
    
    
	console.log(new Set(arguments));//Set(2) { 1, 2 }
}
func(1,2,1);

什么时候使用Set

1、数组或字符串去重时

console.log([...new Set([1,2,1])]);//[ 1, 2 ]
const s = new Set('abbacbd');
console.log([...s].join(""));//abcd

2、不需要通过下标访问,只需要遍历时
3、为了使用Set提供的方法和属性时(add delete clear has forEach size等)

Map

Map和对象都是键值对的集合
Map和对象的区别:对象─般用字符串当作键
基本数据类型:数字、字符串、布尔值、undefined、null
引用数据类型:对象([]、{}、函数、Set、Map 等)
以上都可以作为Map的键

方法

1、set()添加新成员

const m = new Map();
m.set('age',18).set(true, 'true').set('age',20)
console.log(m);//Map(2) { 'age' => 20, true => 'true' }
//覆盖原来的值

2、get()获取成员

const m = new Map();
m.set('age',18).set(true, 'true').set('age',20)
console.log(m.get('age'));//20
//get 获取不存在的成员,返回undefined
console.log(m.get('true'));//undefined
console.log(m.get(true));//true

2、has()是否包含某值

const m = new Map();
m.set('age',18).set(true, 'true').set('age',20)
console.log(m.has('age'));//true

3、clear()清除所有的数据
4、forEach遍历成员,按照成员添加进集合的顺序遍历
回调函数第一个参数是value值,第二个参数是键key,换成其他的参数名称也可以

const m = new Map();
m.set('age',18).set('name', 'zhangsan').set('age',20)
m.forEach(function(value,key){
    
    
	console.log(key+'=>'+value)
});
console.log('------------------');
m.forEach(function(one,two){
    
    
	console.log(two+'=>'+one)
});

在这里插入图片描述

Map构造函数的参数

1、二维数组

console.log(new Map([
	['name', 'alex'],
	['age',18]
])
);
//Map(2) { 'name' => 'alex', 'age' => 18 }

2、Set、Map 等Set
Set中也必须体现出键和值

const s = new Set([
	['name','alex'],
	['age',18]
]);
console.log(new Map(s));//Map(2) { 'name' => 'alex', 'age' => 18 }
console.log(s);//Set(2) { [ 'name', 'alex' ], [ 'age', 18 ] }

什么时候用Map

1、如果只是需要key -> value的结构,或者需要字符串以外的值做键,使用Map更合适
2、forEach for in
3、size

猜你喜欢

转载自blog.csdn.net/qq_42042158/article/details/125858506