javascript Map object vs Set object

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

    Summary:

    • Use a Set when your dataset needs to be composed of unique values
    • Use a Map when you have pairs of associated data. You map the keys to the values

    Example Set:

    There is a meeting with people coming from different organizations. Some people come from the same organization. We need to compose a list all the different organzations. For this we can use a set since we only want to include every organization once:

    const organization = new Set();
    
    organization.add('org1');
    organization.add('org2');
    organization.add('org3');
    organization.add('org1');
    organization.add('org3');
    organization.add('org1');
    
    for(let org of organization){
      console.log(org);
    }

    Example Map:

    We have a pack of dogs and want to assign an age to each dog. We want to map the unique name of each dog to the age of the dog:

    const dogs = new Map([['fluffy', 10], ['barkie', 13]]);
    
    dogs.forEach((value, key) => console.log(key, value));

    How is Map different from an Object?

    An Object is also a collection of key value pairs and can fulfill often the same purpose as a Map can (which is creating key-value pairs). However, there are some key differences between a Map and an Object:

    • Map is built in Iterable, this allows it to use the for of loop or its implementation of the forEach() method which an plain JS Object cannot use.
    • Map has some nice built in methods on its prototype which makes working with it very nicely. Because al Objects inherit from Object.prototype is has access to more useful methods. For example, the size() method on Map returns the number of keys in the Map.

提交回复
热议问题