给定一个Map, 任务是使用JavaScript将Map的键获取到数组中。
方法1:
- 声明新的Map对象
- 显示Map内容
- 在Map Object上使用keys()方法获取Map的键。
- 然后使用array.from()方法将Map对象转换为数组。
<
!DOCTYPE HTML>
<
html >
<
head >
<
title >
How to convert Map keys to
array in JavaScript ?
<
/ title >
<
/ head >
<
body style = "text-align:center;
" >
<
h1 style = "color:green;
" >
srcmini
<
/ h1 >
<
p id = "GFG_UP" style =
"font-size: 19px;
font-weight: bold;
" >
<
/ p >
<
button onClick = "GFG_Fun()" >
click here
<
/ button >
<
p id = "GFG_DOWN" style =
"color: green;
font-size: 24px;
font-weight: bold;
" >
<
/ p >
<
script >
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
let myMap = new Map().set('GFG', 1).set('Geeks', 2);
up.innerHTML = 'myMap = ("GFG" =>
1, "Geeks" =>
2)';
function GFG_Fun() {
var array = Array.from(myMap.keys());
down.innerHTML = "Elements in array are " + array
+ " and Length of array = " + array.length;
}
<
/ script >
<
/ body >
<
/ html >
输出如下:
在单击按钮之前:
文章图片
单击按钮后:
文章图片
方法二:
- 声明新的Map对象
- 显示Map内容
- 在Map Object上使用[…myMap.keys()]方法以数组的形式获取Map的键。
<
!DOCTYPE HTML>
<
html >
<
head >
<
title >
How to convert Map keys to
array in JavaScript
<
/ title >
<
/ head >
<
body style = "text-align:center;
" >
<
h1 style = "color:green;
" >
srcmini
<
/ h1 >
<
p id = "GFG_UP" style =
"font-size: 19px;
font-weight: bold;
" >
<
/ p >
<
button onClick = "GFG_Fun()" >
click here
<
/ button >
<
p id = "GFG_DOWN" style =
"color: green;
font-size: 24px;
font-weight: bold;
" >
<
/ p >
<
script >
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
let myMap = new Map().set('GFG', 1).set('Geeks', 2);
up.innerHTML = 'myMap = ("GFG" =>
1, "Geeks" =>
2)';
function GFG_Fun() {
var array = [ ...myMap.keys() ];
down.innerHTML = "Elements in array are " + array
+ " and Length of array = " + array.length;
}
<
/ script >
<
/ body >
<
/ html >
【如何在JavaScript中将Map键转换为数组()】输出如下:
在单击按钮之前:
文章图片
单击按钮后:
文章图片
推荐阅读
- 如何在Node.js中将文本转换为语音()
- 如何在PHP中将数组转换为SimpleXML()
- 如何在PHP中将图像转换为base64编码()
- 如何将Mongodb数据库与Node.js连接起来()
- 算法题(如何计算大数的mod())
- 如何在Golang中比较两个字节切片()
- 如何使用单个Dockerfile合并多个基本镜像()
- Pandas如何组合Groupby和多个聚合函数()
- 如何在C#中检查线程是否处于活动状态()