JavaScript的Map和Set
JavaScript的Map和Set
1、map:映射(通过key获得value)、增、删
2、set:增、删、判断是否包含某个元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript学习</title>
<script>
'use strict';
let map = new Map([["东大", 620], ["北航", 670], ["清华", 700]]);
alert(map.get("北航")); //670
map.set("复旦",690); //往映射里加入新的键值
map.delete("清华"); //删除一个键值
</script>
</head>
<body>
</body>
</html>
2. Set
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript学习</title>
<script>
'use strict';
let set = new Set([1,3,3,3,5,7]);
set.add(2);
set.delete(7);
console.log(set.has(3));
</script>
</head>
<body>
</body>
</html>
3. 遍历数组、Map和Set
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript学习</title>
<script>
'use strict';
<!--遍历数组-->
let arr = [2,4];
for (let x of arr)
{
console.log(x);
}
<!--遍历Map-->
let map = new Map([["东大", 620], ["北航", 670]]);
for (let x of map)
{
console.log(x);
}
<!--遍历Set-->
let set = new Set([1,3]);
for (let x of set)
{
console.log(x);
}
</script>
</head>
<body>
</body>
</html>