如何将 Map 转换为 Set,反之亦然?

How can I convert Map to Set and vice versa?

forEach() 方法使用 value 变量两次。上面写着这样做是为了保证Map和Set的兼容性

Source

That’s for compatibility with Map where the callback passed forEach has three arguments. Looks a bit strange, for sure. But may help to replace Map with Set in certain cases with ease, and vice versa.

let set = new Set(["orange", "apple", "banana"]);

set.forEach((value, valueAgain, set) => {
  console.log(valueAgain); //"orange", "apple", "banana"
});

所以,我的问题是 Set 如何转换为 Set,反之亦然?据我了解,这种情况没有特殊的方法。

它没有说任何关于转换的事情。 它说您可以对 MapSet.

使用相同的回调函数
const set = new Set(["oranges", "apples", "bananas"]);
const map = new Map([
  ['cucumber', 500],
  ['tomatoes', 350],
  ['onion',    50]
]);
const print = (value, key) => console.log(value, key);
set.forEach(print)
// oranges oranges
// apples apples
// bananas bananas
map.forEach(print)
// 500 cucumber
// 350 tomatoes
// 50 onion

关键不在于您可以在代码中轻松地将集合替换为地图。如果你这样做,你无论如何都会触及代码,并且重写迭代也没有问题。

真正的好处是它允许编写可以同时处理两者的代码。在您的示例中:

function print(collection) {
    collection.forEach((value, key) => {
        console.log(key, value);
    });
}

const set = new Set(["orange", "apple", "banana"]);
const map = new Map([[1, "peach"], [2, "pear"]]);

print(set); // works
print(map); // works the same