如何在Javascript中使用 .map() 函数对Map的key进行操作

9
当使用Javascript内置的Map时,如何使用.map()迭代键?
我知道可以使用for...of,如下所示:
const map = new Map();

map.set(0, 'Zero');
map.set(1, 'One');
map.set(2, 'Two');

for (let key of map.keys()) {
  console.log(key);
}

但这段代码会失败:
map.keys().map(key => {
  console.log(key);
});
6个回答

6

Map.keys() 返回一个迭代器,你可以使用 spread syntax 展开这个迭代器。

const map = new Map();

map.set(0, 'Zero');
map.set(1, 'One');
map.set(2, 'Two');

[...map.keys()].forEach(key => {
  console.log(key);
})


2
使用 for..of 时无需使用spread,因为它已经符合迭代器协议。 - georg
@georg 哎呀,我的错!!我本来想先展开数组,然后再使用任何一个数组方法的。已经更新了,感谢你指出。 - Code Maniac

4

实际上,这是Array.prototype.map函数,它是为数组定义的,因此使用Array.fromkeys转换为数组,然后使用map函数:

const map = new Map();

map.set(0, 'Zero');
map.set(1, 'One');
map.set(2, 'Two');

console.log(...Array.from(map.keys()).map(key => {
  return key ** 2; // square the keys
}));


3
你可以使用 Array.from() 方法:

const map = new Map();

map.set(0, 'Zero');
map.set(1, 'One');
map.set(2, 'Two');

Array.from(map.keys()).map(key => {
  console.log(key);
});

希望这有所帮助!

1
map.forEach((_,key) => console.log(key));

1

你最好直接使用Array.from映射函数,以避免创建临时数组:

Array.from(map.keys(), k => console.log(k))

另一个更冗长但有帮助的选项是在迭代器原型上重新定义数组迭代方法,从而使它们自动适用于所有迭代器:

// http://www.ecma-international.org/ecma-262/7.0/#sec-%iteratorprototype%-object
const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));

Object.defineProperties(IteratorPrototype, {
    forEach: {
        value: function (fn) {
            let n = 0;

            for (let x of this) {
                fn(x, n++, this);
            }
        },
        enumerable: false
    },
    
    map: {
        value: function (fn) {
            let n = 0, a = [];

            for (let x of this) {
                a.push(fn(x, n++, this));
            }

            return a;
        },
        enumerable: false
    },
    
    reduce: {
        value: function (fn, init) {
            let n = 0;

            if (arguments.length === 1) {
                init = this.next().value;
            }

            for (let x of this) {
                init = fn(init, x, n++, this);
            }

            return init;
        },
        enumerable: false
    },

});


/////

const map = new Map();

map.set('a', 'Zero');
map.set('b', 'One');
map.set('c', 'Two');

map.keys().map(console.log)

console.log(map.values().reduce((o, k) => o + '/' + k));

function* it() {
    yield 'x';
    yield 'y';
    yield 'z';
}

it().map(x => console.log(x))


0

const map = new Map([[0, "Zero"], [1, "One"], [2, "Two"]]);
    
const arr = Array.from(map, (entry) => ({ key: entry[0], value: entry[1] })); 

console.log(arr); 
         


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接