.map() a Javascript ES6 Map?

前端 未结 13 2142
不思量自难忘°
不思量自难忘° 2020-12-04 20:53

How would you do this? Instinctively, I want to do:

var myMap = new Map([[\"thing1\", 1], [\"thing2\", 2], [\"thing3\", 3]]);

// wishful, ignorant thinking
         


        
13条回答
  •  抹茶落季
    2020-12-04 21:12

    Map.prototype.map = function(callback) {
      const output = new Map()
      this.forEach((element, key)=>{
        output.set(key, callback(element, key))
      })
      return output
    }
    
    const myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]])
    // no longer wishful thinking
    const newMap = myMap.map((value, key) => value + 1)
    console.info(myMap, newMap)
    

    Depends on your religious fervor in avoiding editing prototypes, but, I find this lets me keep it intuitive.

提交回复
热议问题