给定一个Map, 任务是使用JavaScript将Map的键获取到数组中。
方法1:
- 声明新的Map对象
- 显示Map内容
- 在Map Object上使用keys()方法获取Map的键。
- 然后使用array.from()方法将Map对象转换为数组。
范例1:这个例子使用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的键。
范例2:本示例使用[…Map.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 >
输出如下:
在单击按钮之前:
单击按钮后:
来源:
https://www.srcmini02.com/68473.html