set和map
set数据结构【一个属性:size;常用的四个方法:
add(),delete(),clear(),has()
】
size:set属性,set的数据大小
1 let set1 = new Set();
2 console.log(set1.size);//结果:0
add():添加数据【返回集合对象,支持链式操作】
1 let r1 = set2.add("lea");
2 console.log(set2);//结果:Set(4) {1, 2, "3", "lea"}
3 console.log(r1);//结果:Set(4) {1, 2, "3", "lea"}
delete():删除某项【不能链式操作】
1 let r2 = set2.delete(1);
2 console.log(r2);//结果:true【删除成功】
3 console.log(set2);//结果:Set(3) {2, "3", "lea"}
4 console.log(set2.delete(1));//结果:false【删除失败】
clear():清除集合数据
1 let r3 = set2.clear(); 2 console.log(set2);//结果:Set(0) {} 3 console.log(r3);//结果:undefined
has():是否存在某个值
let r4 = set2.has(1); console.log(r4);//结果:false
map:键值对,键不只可以是字符串,也可以是其他类型的键
①、普通对象示例:
js:
//object对象的键只能是字符串, let obj0={a:1},obj1={b:1}; obj0.name = "lea"; obj0[obj1] = "test"; obj0[obj0] = "test2";//替代上一项【证明object的键只会是字符串,对象会把键直接转为字符串】 console.log(obj0);
②、新建map:new Map( { [key:value], [key:value], [key:value], ........ } );
js:【注意点:key为"name",只会保留一个】
1 let map0 = new Map([ 2 ["name","lea"], 3 ["tel","13452312321"], 4 ["age","23"], 5 ["name","anna"], 6 [obj0,"lea"], 7 [obj1,"lea"] 8 ]); 9 //key可以是对象; 10 console.log(map0);
示例①,②结果:
map实例的属性和方法
属性:size:获取数据的长度
方法:【
set():增加或修改数据【语法:set(key,value);】,
get(key):查看某项数据。
delete(key):删除数据
】
js:
1 let obj0={a:1},obj1={b:1}; 2 let map0 = new Map([ 3 ["name","lea"], 4 ["tel","13452312321"], 5 ["age","23"], 6 ["name","anna"], 7 [obj0,"lea"], 8 [obj1,"lea"] 9 ]); 10 //增加: 11 map0.set("add",["湖北省","荆州市"]); 12 map0.set(["province","city"],"湖北省荆州市"); 13 //修改 14 map0.set("name","joanna"); 15 console.log(map0); 16 //get(key):查看某项数据。 17 console.log(map0.get("name")); 18 //delete():删除数据 19 console.log(map0.delete("name")); 20 console.log(map0);
结果:
方法:【
has(key):是否存在该键值对
clear():清空
】
js:
let obj0={a:1},obj1={b:1}; let map0 = new Map([ ["name","lea"], ["tel","13452312321"], ["age","23"], ["name","anna"], [obj0,"lea"], [obj1,"lea"] ]); //has(key):是否存在该键值对 console.log(map0.has("name"));//true console.log(map0.has(obj0));//true console.log(map0.has("add"));//false //clear():清空 map0.clear(); console.log(map0.size);//0
result:
方法:【
//keys(),values(),entries()
】
js:
let obj0={a:1},obj1={b:1}; let map0 = new Map([ ["name","lea"], ["tel","13452312321"], ["age","23"], ["name","anna"], [obj0,"lea"], [obj1,"lea"] ]); console.log(map0.keys()); console.log(map0.values()); console.log(map0.entries());
result: