如何在Javascript Set上运行map

How do you run map on a Javascript Set?

本文关键字:运行 map Set Javascript      更新时间:2023-09-26

Javascript有一个Array.prototype.map,但似乎没有对应的set。用Javascript在set上运行map的推荐方式是什么?

编辑:按要求添加示例

users = new Set([1,2,3])
// throws an error: 
// Uncaugh TypeError: users.map is not a function
users.map(n => n*n)

你可以使用

Spread-Operator

扩展语法允许表达式在需要多个参数(用于函数调用)或多个元素(用于数组字面量)或多个变量(用于解构赋值)的地方展开。

在你的Set上像这样映射到Set上。

const s = new Set([1,2,3,4]);
const a = [...s].map( n => n * 2 )
console.log(a)