当前位置:网站首页>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)
边栏推荐
猜你喜欢
sqlmap使用教程大全命令大全(图文)
[MySQL exercises] Chapter 4 · Explore operators in MySQL with kiko
搭建frp进行内网穿透
SQL 入门之第一讲——MySQL 8.0.29安装教程(windows 64位)
SQL连接表(内连接、左连接、右连接、交叉连接、全外连接)
基于学生成绩管理系统(附源代码及数据库)
Ubuntu22.04安装mysql
[Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Part 1)--Component UI
[MySQL exercises] Chapter 2 Basic operations of databases and data tables
【Unity】编辑器扩展-03-拓展Inspector视图
随机推荐
如何升级nodejs版本
力扣 593. 有效的正方形
模块化规范
The torch distributed training
Hematemesis summarizes thirteen experiences to help you create more suitable MySQL indexes
期刊投递时的 Late News Submission 是什么
C语言三子棋(井字棋)小游戏
【云原生&微服务五】Ribbon负载均衡策略之随机ThreadLocalRandom
Linux安装mysql
Kotlin 优点
Aleo Testnet3规划大纲
SQL join table (inner join, left join, right join, cross join, full outer join)
编译器R8问题Multidex
【MySQL中auto_increment有什么作用?】
mysql 数据去重的三种方式[实战]
科目三:右转弯
如何在一台机器上(windows)安装两个MYSQL数据库
状态机动态规划之股票问题总结
I advise those juniors and juniors who have just started working: If you want to enter a big factory, you must master these core skills!Complete Learning Route!
[MySQL exercises] Chapter 2 Basic operations of databases and data tables