我想获得一个具有相同键和值的新Map或Set。
Answers:
使用构造函数克隆地图和集合:
var clonedMap = new Map(originalMap)
var clonedSet = new Set(originalSet)
通过for循环创建新Set的速度比Set构造函数快。尽管程度较小,但Maps也是如此。
const timeInLoop = (desc, loopCount, fn) => {
const d = `${desc}: ${loopCount.toExponential()}`
console.time(d)
for (let i = 0; i < loopCount; i++) {
fn()
}
console.timeEnd(d)
}
const set = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
const setFromForLoop = x => {
const y = new Set()
for (const item of x) y.add(item)
return y
}
const map = new Map([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]])
const mapFromForLoop = x => {
const y = new Map()
for (const entry of x) y.set(...entry)
return y
}
timeInLoop('new Set(set)', 1e5, () => new Set(set))
timeInLoop('setFromForLoop(set)', 1e5, () => setFromForLoop(set))
timeInLoop('new Map(map)', 1e5, () => new Map(map))
timeInLoop('mapFromForLoop(map)', 1e5, () => mapFromForLoop(map))
Set
(尽管并非如此Map
)。