new Map()的基础用法(ES6)

1、Map是什么

Map类型是键值对的有序列表,而键和值都可以是任意类型

Map与Set的区别
  • Set是一种叫做集合的数据结构,Map是一种叫做字典的数据结构

    集合-----是由一堆无序的、相关联的,且不重复的内存结构【数学中称为元素】组成的组合
    字典-----是一些元素的集合。每个元素有一个称作key 的域,不同元素的key 各不相同

  • Set集合是以[值,值]的形式存储元素,
    Map字典是以[键,值]的形式存储

2、增删改查

2.1 size

size属性返回 Map 结构的成员总数。

const map = new Map();
map.set('foo', true);
map.set('bar', false);

map.size // 2
2.2 set()

设置键名key对应的键值为value,然后返回整个 Map 结构

如果key已经有值,则键值会被更新,否则就新生成该键

同时返回的是当前Map对象,可采用链式写法

const m = new Map();
let fn = function(){}

m.set('edition', 6)        // 键是字符串
m.set(fn, 'standard')     // 键是函数
m.set(undefined, 'nah')    // 键是 undefined
m.set(1, 'a').set(2, 'b').set(3, 'c') // 链式操作
2.3 get()

get方法读取key对应的键值,如果找不到key,返回undefined

const m = new Map();

const hello = function() {console.log('hello');};
m.set(hello, 'Hello ES6!') // 键是函数

m.get(hello)  // Hello ES6!
2.4 has()

has方法返回一个布尔值,表示某个键是否在当前 Map 对象之中

const m = new Map();

m.set('edition', 6);
m.set(262, 'standard');
m.set(undefined, 'nah');

m.has('edition')     // true
m.has('years')       // false
m.has(undefined)     // true
2.4 delete()

delete方法删除某个键,返回true。如果删除失败,返回false

const m = new Map();
m.set(undefined, 'nah');
m.has(undefined)     // true

m.delete(undefined)
m.has(undefined)       // false
2.5 clear()

clear方法清除所有成员,没有返回值

let map = new Map();
map.set('foo', true);
map.set('bar', false);

map.size // 2
map.clear()
map.size // 0

3、遍历

  • keys():返回键名的遍历器
  • values():返回键值的遍历器
  • entries():返回所有成员的遍历器
  • forEach():遍历 Map 的所有成员
const map = new Map([
  ['F', 'no'],
  ['T',  'yes'],
]);

//keys()
for (let key of map.keys()) {
  console.log(key);       // "F"  "T"
}

//values()
for (let value of map.values()) {
  console.log(value);    // "no"  "yes"
}

// entries()
for (let item of map.entries()) {
  console.log(item[0], item[1]);
}
// "F" "no"  、"T" "yes"

// 或者
for (let [key, value] of map.entries()) {
  console.log(key, value);
}
// "F" "no" 、"T" "yes"

// 等同于使用map.entries()
for (let [key, value] of map) {
  console.log(key, value);
}
// "F" "no"  、 "T" "yes"

map.forEach(function(value, key, map) {
  console.log(key, value);    // "F" "no"  、 "T" "yes"
});

参考链接:https://mp.weixin.qq.com/s/rNagDuBmJSms-R0EXiaLmQ

  • 32
    点赞
  • 150
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
(function(a){a.N={VERSION:"4.1.0",ROOT_URL:a.L_ROOT_URL||function(){var a=document.getElementsByTagName("script"),b=/\/?newmap[\-\._]?([\w\-\._]*)\.js\??/,c,d,e,f;for(c=0,d=a.length;c<d;c++){e=a[c].src,f=e.match(b);if(f)return f[1]==="include"?"../../dist/":e.replace(b,"")+"/"}return""}(),noConflict:function(){return a.N=this._original,this},_original:a.N}})(this),NUtil={extend:function(a){var b=Array.prototype.slice.call(arguments,1);for(var c=0,d=b.length,e;c2?Array.prototype.slice.call(arguments,2):null;return function(){return a.apply(b,c||arguments)}},tryFuncs:function(){var a=null;for(var b=0,c=arguments.length;b<c;b++){var d=arguments[b];try{a=d();break}catch(e){}}return a},getParameterString:function(a){var b=[];for(var c in a){var d=a[c];if(d!=null&&typeof d!="function"){var e;if(typeof d=="object"&&d.constructor==Array){var f=[],g;for(var h=0,i=d.length;h<i;h++)g=d[h],f.push(encodeURIComponent(g===null||g===undefined?"":g));e=f.join(",")}else e=encodeURIComponent(d);b.push(encodeURIComponent(c)+"="+e)}}return b.join("&")},containsStr:function(a,b){return a.indexOf(b)!=-1},getParameters:function(a){a=a===null||a===undefined?window.location.href:a;var b="";if(NUtil.containsStr(a,"?")){var c=a.indexOf("?")+1,d=NUtil.containsStr(a,"#")?a.indexOf("#"):a.length;b=a.substring(c,d)}var e={},f=b.split(/[&;]/);for(var g=0,h=f.length;g<h;++g){var i=f[g].split("=");if(i[0]){var j=i[0];try{j=decodeURIComponent(j)}catch(k){j=unescape(j)}var l=(i[1]||"").replace(/\+/g," ");try{l=decodeURIComponent(l)}catch(k){l=unescape(l)}l=l.split(","),l.length==1&&(l=l[0]),e[j]=l}}return e},urlAppend:function(a,b){var c=a;if(b){var d=(a+" ").split(/[?&]/);c+=d.pop()===" "?b:d.length?"&"+b:"?"+b}return c},upperCaseObject:function(a){var b={};for(var c in a)b[c.toUpperCase()]=a[c];return b},createUrlObject:function(a,b){b=b||{};if(!/^\w+:\/\//.test(a)){var c=window.location,d=c.port?":"+c.port:"",e=c.protocol+"//"+c.host.split(":").shift()+d;if(a.indexOf("/")===0)a=e+a;else{var f=c.pathname.split("/");f.pop(),a=e+f.join("/")+"/"+a}}b.ignoreCase&&(a=a.toLowerCase());var g=document.createElement("a");g.href=a;var h={};h.host=g.host.split(":").shift(),h.protocol=g.protocol,b.ignorePort80?h.port=g.port=="80"||g.port=="0"?"":g.port:h.port=g.port==""||g.port=="0"?"80":g.port,h.hash=b.ignoreHash||g.hash==="#"?"":g.hash;var i=g.search;if(!i){var j=a.indexOf("?");i=j!=-1?a.substr(j):""}return h.args=NUtil.getParameters(i),h.pathname=g.pathname.charAt(0)=="/"?g.pathname:"/"+g.pathname,h},stamp:function(){var a=0,b="_newmap_id";return function(c){return c[b]=c[b]||"_newmap_id_"+ ++a,c[b]}}(),requestAnimFrame:function(){function a(a){window.setTimeout(a,1e3/60)}var b=window.requestAnimationFrame||
回答: ES6中的Set和Map是两种新增的集合类型。Set是一种无重复值的集合,可以通过new Set()来创建。它具有add方法用于向集合中添加元素,has方法用于判断集合中是否存在某个元素,clear方法用于清空集合。Set也可以用于数组去重,通过new Set(\[...\])的方式将数组转换为Set,利用Set的特性去除重复值。\[1\] Map是一种键值对的集合,可以通过new Map()来创建。它具有set方法用于向集合中添加键值对,get方法用于获取指定键名对应的值,has方法用于判断集合中是否存在某个键名,clear方法用于清空集合。Map的键名可以是任意数据类型,包括引用值,但需要注意的是,引用值作为键名时,需要使用相同的引用地址才能获取到对应的值。\[2\] Set和Map都可以使用for...of循环或forEach方法进行遍历。在Set中,forEach的第二个参数是集合的元素,因为Set中不存在下标。而在Map中,forEach的第一个参数是键值对的值,第二个参数是键值对的键名。\[3\] 总结来说,Set和MapES6中新增的集合类型,Set用于存储无重复值的集合,Map用于存储键值对的集合。它们提供了一些方法来操作集合,如添加、获取、判断是否存在等。在使用时需要注意它们的特性和方法的使用方式。 #### 引用[.reference_title] - *1* *2* [ES6中的Map和Set详解](https://blog.csdn.net/m0_45093055/article/details/126430467)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [ES6中的set与map](https://blog.csdn.net/weixin_44247866/article/details/127561391)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值