Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Keyed collections

This chapter introduces collections of data which are indexed by a key;Map andSet objects contain elements which are iterable in the order of insertion.

Maps

Map object

AMap object is a key/value map that can iterate its elements in insertion order.

The following code shows some basic operations with aMap. See also theMap reference page for more examples and the complete API. You can use afor...of loop to return an array of[key, value] for each iteration.

js
const sayings = new Map();sayings.set("dog", "woof");sayings.set("cat", "meow");sayings.set("elephant", "toot");sayings.size; // 3sayings.get("dog"); // woofsayings.get("fox"); // undefinedsayings.has("bird"); // falsesayings.delete("dog");sayings.has("dog"); // falsefor (const [key, value] of sayings) {  console.log(`${key} goes ${value}`);}// "cat goes meow"// "elephant goes toot"sayings.clear();sayings.size; // 0

Object and Map compared

Traditionally,objects have been used to map strings to values. Objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key.Map objects, however, have a few more advantages that make them better maps.

  • The keys of anObject arestrings orsymbols, whereas they can be of any value for aMap.
  • You can get thesize of aMap easily, while you have to manually keep track of size for anObject.
  • The iteration of maps is in insertion order of the elements.
  • AnObject has a prototype, so there are default keys in the map. (This can be bypassed usingmap = Object.create(null).)

These three tips can help you to decide whether to use aMap or anObject:

  • Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
  • Use maps if there is a need to store primitive values as keys because object treats each key as a string whether it's a number value, boolean value or any other primitive value.
  • Use objects when there is logic that operates on individual elements.

WeakMap object

AWeakMap is a collection of key/value pairs whose keys must be objects ornon-registered symbols, with values of any arbitraryJavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in aWeakMap does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in anyWeakMap become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. The only primitive type that can be used as aWeakMap key is symbol — more specifically,non-registered symbols — because non-registered symbols are guaranteed to be unique and cannot be re-created.

TheWeakMap API is essentially the same as theMap API. However, aWeakMap doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration. So there is no method to obtain a list of the keys in aWeakMap. If there were, the list would depend on the state of garbage collection, introducing non-determinism.

For more information and example code, see also "Why WeakMap?" on theWeakMap reference page.

One use case ofWeakMap objects is to store private data for an object, or to hide implementation details. The following example is from Nick Fitzgerald's blog post"Hiding Implementation Details with ECMAScript 6 WeakMaps". The private data and methods belong inside the object and are stored in theprivates object, which is aWeakMap. Everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world becauseprivates is not exported from the module.

js
const privates = new WeakMap();function Public() {  const me = {    // Private data goes here  };  privates.set(this, me);}Public.prototype.method = function () {  const me = privates.get(this);  // Do stuff with private data in `me`  // …};module.exports = Public;

Sets

Set object

Set objects are collections of unique values. You can iterate its elements in insertion order. A value in aSet may only occur once; it is unique in theSet's collection.

The following code shows some basic operations with aSet. See also theSet reference page for more examples and the complete API.

js
const mySet = new Set();mySet.add(1);mySet.add("some text");mySet.add("foo");mySet.has(1); // truemySet.delete("foo");mySet.size; // 2for (const item of mySet) {  console.log(item);}// 1// "some text"

Converting between Array and Set

You can create anArray from a Set usingArray.from or thespread syntax. Also, theSet constructor accepts anArray to convert in the other direction.

Note:Set objects storeunique values—so any duplicate elements from an Array are deleted when converting!

js
Array.from(mySet);[...mySet2];mySet2 = new Set([1, 2, 3, 4]);

Array and Set compared

Traditionally, a set of elements has been stored in arrays in JavaScript in a lot of situations. TheSet object, however, has some advantages:

  • Deleting Array elements by value (arr.splice(arr.indexOf(val), 1)) is very slow.
  • Set objects let you delete elements by their value. With an array, you would have tosplice based on an element's index.
  • The valueNaN cannot be found withindexOf in an array.
  • Set objects store unique values. You don't have to manually keep track of duplicates.

WeakSet object

WeakSet objects are collections of garbage-collectable values, including objects andnon-registered symbols. A value in theWeakSet may only occur once. It is unique in theWeakSet's collection.

The main differences to theSet object are:

  • In contrast toSets,WeakSets arecollections ofobjects or symbols only, and not of arbitrary values of any type.
  • TheWeakSet isweak: References to objects in the collection are held weakly. If there is no other reference to an object stored in theWeakSet, they can be garbage collected. That also means that there is no list of current objects stored in the collection.
  • WeakSets are not enumerable.

The use cases ofWeakSet objects are limited. They will not leak memory, so it can be safe to use DOM elements as a key and mark them for tracking purposes, for example.

Key and value equality of Map and Set

Both the key equality ofMap objects and the value equality ofSet objects are based on theSameValueZero algorithm:

  • Equality works like the identity comparison operator===.
  • -0 and+0 are considered equal.
  • NaN is considered equal to itself (contrary to===).

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp