JavaScript 的 Map数据结构

等级 4266 次按键

这演示了使用Map存储键值对并遍历它们。

JavaScript 代码

// 创建一个新的Map(键值集合)
// 与对象不同,键可以是任何类型
1const scores = new Map();
2
// set()添加或更新键值对
3scores.set("Alice", 95);
4scores.set("Bob", 87);
5scores.set("Carol", 92);
6
// get()获取键的值
7console.log(scores.get("Alice"));
// has()检查键是否存在
8console.log(scores.has("Dave"));
// size属性返回条目数量
9console.log(scores.size);
10
// forEach遍历条目
// 回调接收(值, 键, map)
11scores.forEach((score, name) => {
12 console.log(`${name}: ${score}`);
13});

运行结果

95
false
3
Alice: 95
Bob: 87
Carol: 92
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 JavaScript 代码中需要输入的符号及其出现次数。

  • (× 12
  • )× 12
  • .× 11
  • "× 10
  • ;× 9
  • ,× 4
  • {× 3
  • }× 3
  • `× 2
  • =× 2

JavaScript 等级 4 的更多代码示例

← 返回 JavaScript 打字练习