简体   繁体   中英

How can I set initial values for map with new Map()?

We can do

let myMap = new Map()

myMap.set(keyString, "value associated with 'a string'")
myMap.set(keyObj, 'value associated with keyObj')
myMap.set(keyFunc, 'value associated with keyFunc')

which will work like:

myMap.get(keyString)    // "value associated with 'a string'"
myMap.get(keyObj)       // "value associated with keyObj"
myMap.get(keyFunc)      // "value associated with keyFunc"

But this process will become cumbersome if you have very large data. So is there a way like:

let myMap = new Map({
  keyString: value1 
  keyObj:value2
  keyFunc: value3
})

I know the above code is wrong, but I want to know is there a way to do that?

Based on the reference page from MDN for Map, you could do it as follows:

let kvArray = [['key1', 'value1'], ['key2', 'value2']]

// Use the regular Map constructor to transform a 2D key-value Array into a map
let myMap = new Map(kvArray)

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