可以初始化构建一个空的Map对象,再添加键值对
(相关资料图)
var map = new Map(); map.set("name","zhangsan"); map.set("age",40);
也可以直接用一个二维数组构造一个Map对象,如:
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"]])
get方法可以通过给定的键,查询到Map的值
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"]]); map.get("age") //返回40 map.get("name") //返回wangqiang
set方法可以向map中添加一个键值对,如果map中键已经存在,则修改该键的值。
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"]]); map.set("age",38); map.set("address","tianhe guangzhou"); for (let item of map){ console.log(item[0],":",item[1]); //遍历可以看到添加的键值对 }
delete方法可以通过给定的键,删除掉map的值
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"]]); map.delete("age")
has方法可以查询给定的键是否存在
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"]]); map.delete("age") map.has("age") // false;
通过for(...of...){...}可以对map的内容进行遍历
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"],["address","tianhe"]]); for (let item of map){ console.log(item[0],item[1]); }
除了通过上面提到的for(... of ...){...}循环进行遍历,还可以使用迭代器进行遍历
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"],["address","tianhe"]]); var entries = map.entries(); //获取一个迭代器 for (;;){ let entry = entries.next(); //迭代 if (entry.done){ //迭代是否完成 break; } console.log(entry.value[0],":",entry.value[1]); }
clear方法清空map的键值对
var map = new Map([["name","wangqiang"],["age",40],["city","guangzhou"]]); map.clear(); map.size(); //0
文章同时发表在:码农编程网欢迎访问
本节重点:
标签
Copyright ? 2015-2022 北方粮油网版权所有 备案号:京ICP备2021034106号-50 联系邮箱: 55 16 53 8@qq.com