javascript Map object vs Set object

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

    var obj = {};
    obj.name= "Anand Deep Singh";
    console.log(obj.name); //logs "Anand Deep Singh"
    

    similarly in ES6, we can use regular object.

    var map = new Map();
    map.set("name","Anand Deep Singh");
    console.log(map.get("name")); //logs "Anand Deep Singh"
    

    But noticeable thing is a Map isn’t created with the literal object syntax, and that one uses set and get methods to store and access data.

    It has a has method to check whether the key exists in the object or not, delete method to delete the object and clear method to clear the entire object.

    Set is a unique list of values. It’s simply a unique list.

    var set = new Set(["a", "a","e", "b", "c", "b", "b", "b", "d"]);
    console.log(set); //logs Set {"a", "e", "b", "c", "d"}
    

    A Set can’t be accessed like an array, and it provides the same methods as a Map.

提交回复
热议问题