javascript Map object vs Set object

后端 未结 4 1552
我寻月下人不归
我寻月下人不归 2021-02-01 13:21

JavaScript Map and Set objects are both iterable objects. Both store object by [key, value] pair. I want to know when to use what? Is there any preference one over

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 13:41

    There are two main data structures:

    • Objects: are used for storing keyed collections.
    • Arrays: are used for storing ordered collections.

    But that’s not enough for real life. That’s why Map and Set also exist.

    • Map: is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

    For instance:

    let map = new Map();
    
    map.set('1', 'str1');   // a string key
    map.set(1, 'num1');     // a numeric key
    map.set(true, 'bool1'); // a boolean key
    
    
    let hamid = { name: "Hamid" };
    // john is the key for the map
    map.set(hamid, 123);
    
    • Set : is a special type collection – “set of values” (without keys), where each value may occur only once.

    instance:

    let set = new Set();
    
    let hamid= { name: "Hamid" };
    let pete = { name: "Pete" };
    let mary = { name: "Mary" };
    
    // visits, some users come multiple times
    set.add(hamid);
    set.add(pete);
    set.add(mary);
    set.add(hamid);
    set.add(mary);
    
    // set keeps only unique values
    alert( set.size ); // 3
     
    

    https://javascript.info/map-set

提交回复
热议问题