The use of map objects in ES6 is indeed better than Object.

Map object

Map objects hold key-value pairs. Any value (object or primitive) can be used as a key or a value.
We can use various types as the keys and values ​​of the map.

Difference between Maps and Objects

  • We generally use strings or Symbols for the keys of Objects;
    the keys of Maps can be of any type, such as: functions, arrays, objects, NANs, and so on.

  • The length of Object can be obtained through keys or the length of key array; the length of
    Map can be obtained directly through the attribute size.

Map key:

Use the set function to add a key-value pair to the map object, the parameter is (key name, value);
use the get function to get the value of the current key, the parameter is (key name);
use the delete function to delete the current key-value pair, The parameter is (the name of the key);
use the size attribute to get the number of key-value pairs of the current map object.

 		let mapObj = new Map()
        // String
        mapObj.set('name',"六卿")
        mapObj.set('age',18)
        mapObj.set('habby',['唱歌'])
        mapObj.set('loves',{
    
    
            'apple':"100%",
            'orange':"10%",
        })
        let a = ()=>{
    
    console.log("执行了a函数")}
        // fun
        mapObj.set(a,a)
        mapObj.set(NaN,'NaN')
        console.log(mapObj.has('habby'))
        console.log(mapObj.get('age'))
        console.log(mapObj.size)
        mapObj.get(a)()

insert image description here

Loop Map

1. Use for of
        let mapObj = new Map()
        mapObj.set('name',"六卿")
        mapObj.set('age',18)
        mapObj.set('habby',['唱歌'])
        mapObj.set('loves',{
    
    
            'apple':"100%",
            'orange':"10%",
        })
        let a = ()=>{
    
    console.log("执行了a函数")}
        mapObj.set(a,a)
        mapObj.set(NaN,'NaN')
        mapObj.get(a)()
        for(let key  of mapObj){
    
    
            console.log(key)//[name,'张俊卿']  [age,18]  [habby,['唱歌']]....
        }

The let key of the loop is an array, the first item of the array is the key of the map object, and the second item is the value corresponding to the key.

1. Use forEach
        let mapObj = new Map()
        mapObj.set('name',"六卿")
        mapObj.set('age',18)
        mapObj.set('habby',['唱歌'])
        mapObj.set('loves',{
    
    
            'apple':"100%",
            'orange':"10%",
        })
        let a = ()=>{
    
    console.log("执行了a函数")}
        mapObj.set(a,a)
        mapObj.set(NaN,'NaN')
        mapObj.get(a)()
        mapObj.forEach((value,key)=>{
    
    
            console.log(value,key)
        })

insert image description here
forEach passes in the callback function. The first parameter of the callback function is the value of each key-value pair, and the second parameter is the key of each key-value pair.

Guess you like

Origin blog.csdn.net/qq_43291759/article/details/123425459