简体   繁体   中英

What is a practical use of objects as keys within JS Map dataype?

I've recently been reading into Javascript's Map datatype (NOT the map() array method). MDN Reference

I've read and followed various tutorials/articles showing the similarities and differences between Maps, Arrays and 'standard' Objects. One unique property of Maps is that you can use any datatype as a key, including an Object.

There are many examples out there, such as this one from Tania Rascia

// Create an object
const objAsKey = { foo: 'bar' }

const map = new Map()

// Set this object as the key of a Map
map.set(objAsKey, 'What will happen?')

Here's the console output:

key: {foo: "bar"}
value: "What will happen?"

What I'm asking is, what is a benefit of this possibility? Why would I ever need to use an object as a key?

From my tweets on the subject:

Say you have an object (like a DOM element) that you want to associate some data with, but you don't want to modify the object to add the data directly to it. So you use a Map with the object as key and your associated data as value.

typically, you'd want to use a WeakMap for this, so that if the original object goes away (garbage collected) the data is also released.

but a reason to use map instead of weakmap is that map is iterable and weakmap isn't.

so if you're willing to trade out that you need to do more manual work to manage the map entries (for cleaner garbage collection), then you get the ability to enumerate all the entries of the map, which can be useful in certain cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM