如何将地图转换为设置,反之亦然?

发布于 2025-01-22 21:37:09 字数 1019 浏览 2 评论 0原文

foreach()方法使用value变量两次。写道是为了确保地图和设置的兼容性。

这是与MAP的兼容性,在该地图上通过的回调foreach有三个参数。肯定看起来有些奇怪。但可能有助于在某些情况下轻松替换设置的地图,反之亦然。

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

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

因此,我的问题是如何将设置转换为集合,反之亦然?据我了解,这种情况没有特殊方法。

forEach() method uses value variable twice. It's written that this is done in order to ensure the compatibility of Map and 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"
});

So, my question is how Set can convert into Set and vice versa? As I understand, there is no special method for this case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

友欢 2025-01-29 21:37:09

关键不是您可以轻松地用代码中的地图替换一组。如果这样做,您无论如何都可以触摸代码,并且也不会重写迭代。

真正的好处是,它允许编写可以立即处理两个可以处理的代码。在您的示例中:

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

The point is not that you can easily replace a set with a map in your code. If you do that, you touch the code anyway, and would have no trouble also rewriting the iteration.

The real benefit is that it allows writing code that can handle both at once. In your example:

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

岛徒 2025-01-29 21:37:09

关于转换,它没有说什么。
它说您可以使用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

It does not say anything about conversion.
It says that you can use the same function callback for the Map and the Set.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文