javascript Map object vs Set object

后端 未结 4 1492
我寻月下人不归
我寻月下人不归 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:31

    Provided you are talking about the ES6 types, they aren't the same data structure even though the Set might be implemented with a Map.

    Your definition of Map is right, but a Set is a collection of unique values, unlike an array which can have duplicates.

    var array = [1, 2, 3, 3];
    
    var set = new Set(array); // Will have [1, 2, 3]
    assert(set.size, 3);
    
    var map = new Map();
    map.set('a', 1);
    map.set('b', 2);
    map.set('c', 3);
    map.set('C', 3);
    map.set('a', 4); // Has: a, 4; b, 2; c: 3, C: 3
    assert(map.size, 4);
    

提交回复
热议问题