在JavaScript中,遍歷一個map對象有以下幾種方法:
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of myMap) {
console.log(`${key} = ${value}`);
}
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
myMap.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of myMap.entries()) {
console.log(`${key} = ${value}`);
}
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let key of myMap.keys()) {
console.log(key);
}
for (let value of myMap.values()) {
console.log(value);
}
這些方法可以根據具體的需求選擇使用,以便輕松遍歷map對象的鍵、值或鍵值對。