当前位置:网站首页>7. JS ES6新增语法 new Map详讲,还有一道代码实战案例帮你快上手new Map
7. JS ES6新增语法 new Map详讲,还有一道代码实战案例帮你快上手new Map
2022-07-31 08:39:00 【道长道长IOT】
我愿称new Map为最强
最近刷力扣我才发现,他是真好用,下面我来给大家介绍一下new Map的具体使用
1.new Map其实就是一个键值对的集合,类似于这样
let map = new Map([[key,value],[key,value]])
2.我们先来看new Map的set属性,通过set可以给map新增属性
let map = new Map()
map.set('老6',1)
console.log(map);
//打印结果:Map(1) { '老6' => 1 }
//但是假如我们执行map.set('老6',2),那么之前的map内容会被覆盖,换成新的这个,同时map的size属性不会改变
3.我们来看new Map的size属性,size可以返回map的一个数量
let map = new Map()
map.set('老6',1)
console.log(map.size)
//1
4.我们来看new Map的get属性,get可以读取map中key所对应的value,也就是他的值,如果有,则返回,如果没有,返回一个undefined
let map = new Map()
map.set("老6", '老6很光荣')
map.get('老6')
// 老6很光荣
map.get('老8')
// undefined
5.我们来看new Map的has属性,如果有key,返回true,如果没有返回false
let map = new Map()
map.set("老6", '老6很光荣')
map.has('老6')// true
6.还有删除,清除
let map = new Map()
map.delete(key)
map.clear()
最后,我们来做一道算法题,让大家充分的了解new Map的使用
题目:判断数组是否有重复元素,有返回true,没有返回false
function containsDuplicate(nums) {
、
//定义一个map
let map = new Map()
//使用for of 循环数组
for(const item of nums){
//如果在map中找到了这个item,证明有重复的
if (map.has(item)) {
return true
}
//如果前面没找到,那么就把当前循环的这一项存储进去
map.set(item)
}
};
const nums = [1,2,3,1,3]
containsDuplicate(nums)
边栏推荐
- 【Unity】编辑器扩展-03-拓展Inspector视图
- Small application project development, jingdong mall 】 【 uni - app custom search component (below) - search history
- 深度学习随机数设置,保证实验的可重复性
- mysql安装教程【安装版】
- 日志导致线程Block的这些坑,你不得不防
- 文件管理:目录管理
- [转载] Virtual Studio 让系统找到需要的头文件和库
- SSM integration case study (detailed)
- [Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Part 1)--Component UI
- 《如何戒掉坏习惯》读书笔记
猜你喜欢

【RISC-V】risc-v架构学习笔记(架构初学)

PowerCLi 一键批量部署OVA 到esxi 7

关于Error EPERM operation not permitted, mkdir...几种解决办法的比较

A brief introduction to the SSM framework

Small application project development, jingdong mall 】 【 uni - app custom search component (below) - search history

PowerCLi 通过自建PXE Server一键esxi7下批量部署常规New-VM

SSM framework explanation (the most detailed article in history)

服务器上解压文件时提示“gzip: stdin: not in gzip format,tar: Child returned status 1,tar: Error is not recovera“

MySQL安装教程

SQL statement knowledge
随机推荐
二维坐标工具API
[转载] Virtual Studio 让系统找到需要的头文件和库
[What is the role of auto_increment in MySQL?】
SQL连接表(内连接、左连接、右连接、交叉连接、全外连接)
UML图及在drawio中的绘制
【云原生&微服务五】Ribbon负载均衡策略之随机ThreadLocalRandom
【小程序专栏】总结uniapp开发小程序的开发规范
Job hunting product manager [9] How to write a good resume in job hunting season?
状态机动态规划之股票问题总结
刷题《剑指Offer》day06
JSP pagecontext对象的简介说明
免安装版的Mysql安装与配置——详细教程
Pytorch学习记录(七):自定义模型 & Auto-Encoders
【黄啊码】MySQL入门—3、我用select ,老板直接赶我坐火车回家去,买的还是站票
google搜索技巧——程序员推荐
全国中职网络安全B模块之国赛题远程代码执行渗透测试 PHPstudy的后门漏洞分析
SSM integration case study (detailed)
SQLAlchemy使用教程
【C#】说说 C# 9 新特性的实际运用
0730~Mysql优化