ES6地图功能

ES6 map feature

本文关键字:功能 地图 ES6      更新时间:2023-09-26

我正在尝试es6地图数据结构,但是当我试图迭代地图时,它会给出以下错误

The error occurs on line 6:
for (let [key, val] of m.entries())
SyntaxError: Unexpected token [
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3
下面是我的代码:
"use strict"
let m = new Map()
m.set("hello", 42)
m.set(1, 34);
console.log(m);
for (let [key, val] of m.entries())
    console.log(key + " = " + val)

这是更方便的迭代解决方案:

let m = new Map();
m.set("hello", 42);
m.set(1, 34);
for (var [key, value] of m) {
    console.log(key + " = " + value);
}

我找到了一个解决方案,下面是迭代es6 map的代码片段:

"use strict"
let m = new Map()
m.set("hello", 42)
m.set(1, 34);
for (let entry of m.entries())
    console.log(entry[0]+" "+entry[1]);