Map 객체는 키-값 쌍을 저장하며 각 쌍의 삽입 순서도 기억합니다. 아무 값(객체, 원시 값)이나 키 또는 값으로 사용할 수 있습니다.

구문

new Map([iterable])

매개변수

iterable
요소가 키-값 쌍인, Array 또는 다른 순회 가능한 객체(예: [[1, 'one'], [2, 'two']]). 각 키-값 쌍은 새로운 Map에 포함됩니다. null 값은 undefined로 취급합니다.

설명

Map 객체는 요소의 삽입 순서대로 원소를 순회합니다. for...of 반복문은 각 순회에서 [key, value]로 이루어진 배열을 반환합니다.

키 동일성

key 동일성은 sameValueZero 알고리즘에 기초합니다. NaN은 (NaN !== NaN이지만) NaN과 일치한다고 간주하며, 다른 모든 값은 === 연산자의 결과를 따릅니다. 지금의 ECMAScript 명세에서는 -0+0이 같지만 초기 명세에서는 그렇지 않았습니다. 브라우저 호환성의 "Key equality for -0 and 0"을 참고하세요.

ObjectMap 비교

Object는 값에 키를 할당할 수 있고, 그 키로 값을 얻을 수 있고, 키를 삭제할 수 있으며 어떤 키에 값이 존재하는지 확인할 수 있다는 점에서 Maps와 유사합니다. 이러한 이유와, 내장 대체제가 없었기 때문에 역사적으로 ObjectMap 대신 사용하곤 했습니다. 그러나 어떤 상황에선 Map을 고려해야 할 몇 가지 중요한 차이점이 있습니다.

  • Object의 키에는 StringSymbol을 사용할 수 있지만, Map은 함수, 객체, 원시 자료형 등 어떤 값도 사용할 수 있습니다.
  • Map의 키는 삽입순으로 정렬되지만 Object의 키는 그렇지 않습니다. 따라서 Map을 순회하면 키를 삽입한 순서대로 반환합니다.
  • Map의 크기는 size 속성으로 쉽게 얻을 수 있지만 Object의 속성 수는 직접 판별해야 합니다.
  • Map은 바로 순회할 수 있지만, Object를 순회하려면 어떤 방법이든 키의 배열을 얻고, 그 배열을 순회해야 합니다.
  • Object는 프로토타입을 가지므로, 주의하지 않으면 키가 충돌할 수 있습니다. ES5부터는 Object.create(null)을 사용해도 되지만 거의 쓰이지 않습니다.
  • 잦은 키의 추가와 제거가 필요한 시나리오에서는 Map이 더 빠릅니다.

속성

Map.length
값이 0인 속성입니다.
요소의 수는 Map.prototype.size로 알아낼 수 있습니다.
get Map[@@species]
파생 객체를 생성하는데 사용하는 생성자 함수입니다.
Map.prototype
Map 생성자의 프로토타입을 나타냅니다. 모든 Map 인스턴스에 속성을 추가할 수 있습니다.

Map 인스턴스

모든 Map 인스턴스는 Map.prototype을 상속받습니다.

속성

Map.prototype.constructor
인스턴스의 프로토타입을 만드는 함수를 반환한다. 이것 Map 함수의 기본 값이다.
Map.prototype.size
Map 객체에 들어있는 key/value pair의 수를 반환한다.

메서드

Map.prototype.clear()
Map 객체의 모든 key/value pair를 제거한다.
Map.prototype.delete(key)
주어진 키(Key)와 해당되는 값(Value)를 제거하고 제거하기 전에 Map.prototype.has(key)가 반환했던 값을 반환한다. 그 후의 Map.prototype.has(key)는 false를 반환한다.
Map.prototype.entries()
Map 객체 안의 모든 요소들을 [key, value] 형태의 array 로 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
Map.prototype.forEach(callbackFn[, thisArg])
Map 객체 안에 존재하는 각각의 key/value pair에 집어넣은 순서대로 callbackFn을 부른다. 만약 thisArg 매개변수가 제공되면, 이것이 각 callback의 this 값으로 사용된다.
Map.prototype.get(key)
주어진 키(Key)에 해당되는 값(value)을 반환하고, 만약 없으면 undefined를 반환한다.
Map.prototype.has(key)
Map 객체 안에 주어진 key/value pair가 있는지 검사하고 Boolean 값을 반환한다.
Map.prototype.keys()
Map 객체 안의 모든 키(Key)들을 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
Map.prototype.set(key, value)
Map 객체에 주어진 키(Key)에 값(Value)를 집어넣고, Map 객체를 반환한다.
Map.prototype.values()
Map 객체 안의 모든 (Value)들을 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
Map.prototype[@@iterator]()
Map 객체 안의 모든 요소들을 [key, value] 형태의 array 로 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.

예제

Map 객체 사용하기

var myMap = new Map();

var keyString = "어떤 문자열",
    keyObj = {},
    keyFunc = function () {};

// 값 저장하기
myMap.set(keyString, "'어떤 문자열'과 연결된 값");
myMap.set(keyObj, "keyObj와 연결된 값");
myMap.set(keyFunc, "keyFunc와 연결된 값");

myMap.size; // 3

// 값 불러오기
myMap.get(keyString);    // "'어떤 문자열'과 연결된 값"
myMap.get(keyObj);       // "keyObj와 연결된 값"
myMap.get(keyFunc);      // "keyFunc와 연결된 값"

myMap.get("a string");   // "'어떤 문자열'과 연결된 값"
                         // 왜냐면 keyString === 'a string'
myMap.get({});           // undefined, keyObj !== {}
myMap.get(function() {}) // undefined, keyFunc !== function () {}

Map의 키로 NaN 사용하기

NaN도 키로 사용할 수 있습니다. 모든 NaN은 자기 자신과 동일하지 않지만(NaN !== NaN), NaN을 구분할 수도 없기 때문에 아래 예제도 잘 동작합니다.

var myMap = new Map();
myMap.set(NaN, "not a number");

myMap.get(NaN); // "not a number"

var otherNaN = Number("foo");
myMap.get(otherNaN); // "not a number"

for..ofMap 순회하기

Mapfor..of 반복문을 사용해 순회할 수 있습니다.

var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}
// 0 = zero
// 1 = one

for (var key of myMap.keys()) {
  console.log(key);
}
// 0
// 1

for (var value of myMap.values()) {
  console.log(value);
}
// zero
// one

for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}
// 0 = zero
// 1 = one

forEach()Map 순회하기

MapforEach() 메서드로 순회할 수 있습니다.

myMap.forEach(function(value, key) {
  console.log(key + " = " + value);
});
// 2개의 로그를 출력한다; 첫 번째는 "0 = zero"이며 두 번째는 "1 = one"이다

Array 객체와의 관계

var kvArray = [["key1", "value1"], ["key2", "value2"]];

// 2D Array를 일반적인 Map constructor를 이용하여 Map 인스턴스를 만든다.
var myMap = new Map(kvArray);

myMap.get("key1"); // returns "value1"

// Spread 연사자를 이용하여 map을 2D key-value Array로 변환한다.
console.log(uneval([...myMap])); // Will show you exactly the same Array as kvArray

// 혹은 keys나 values iterator에 spread operator를 사용하여 키나 값들의 Array를 얻는다.
console.log(uneval([...myMap.keys()])); // Will show ["key1", "key2"]

명세

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Map' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Map' in that specification.
Draft  

브라우저 호환성

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
MapChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
new Map(iterable)Chrome Full support 38Edge Full support 12Firefox Full support 13IE No support NoOpera Full support 25Safari Full support 9WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12
new Map(null)Chrome Full support YesEdge Full support 12Firefox Full support 37IE Full support 11Opera Full support YesSafari Full support 9WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support 12Firefox Android Full support 37Opera Android Full support YesSafari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
Map() without new throwsChrome Full support YesEdge Full support 12Firefox Full support 42IE Full support 11Opera Full support YesSafari Full support 9WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support 12Firefox Android Full support 42Opera Android Full support YesSafari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12
Key equality for -0 and 0Chrome Full support 38Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 25Safari Full support 9WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 29Opera Android Full support 25Safari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 4.0.0
clearChrome Full support 38Edge Full support 12Firefox Full support 19IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 19Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
deleteChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
entriesChrome Full support 38Edge Full support 12Firefox Full support 20IE No support NoOpera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 20Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
forEachChrome Full support 38Edge Full support 12Firefox Full support 25IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 25Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
getChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support Yes
hasChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support Yes
keysChrome Full support 38Edge Full support 12Firefox Full support 20IE No support NoOpera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 20Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
prototypeChrome Full support 38Edge Full support 12Firefox Full support 13IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support Yes
setChrome Full support 38Edge Full support 12Firefox Full support 13IE Partial support 11
Notes
Partial support 11
Notes
Notes Returns 'undefined' instead of the 'Map' object.
Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 14Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support Yes
sizeChrome Full support 38Edge Full support 12Firefox Full support 19
Notes
Full support 19
Notes
Notes From Firefox 13 to Firefox 18, the size property was implemented as a Map.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
IE Full support 11Opera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 19
Notes
Full support 19
Notes
Notes From Firefox 13 to Firefox 18, the size property was implemented as a Map.prototype.size() method, this has been changed to a property in later versions conform to the ECMAScript 2015 specification.
Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
valuesChrome Full support 38Edge Full support 12Firefox Full support 20IE No support NoOpera Full support 25Safari Full support 8WebView Android Full support 38Chrome Android Full support 38Edge Mobile Full support 12Firefox Android Full support 20Opera Android Full support 25Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
@@iteratorChrome Full support YesEdge Full support YesFirefox Full support 36
Full support 36
No support 27 — 36
Notes Alternate Name
Notes A placeholder property named @@iterator is used.
Alternate Name Uses the non-standard name: @@iterator
No support 17 — 27
Notes Alternate Name
Notes A placeholder property named iterator is used.
Alternate Name Uses the non-standard name: iterator
IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 36
Full support 36
No support 27 — 36
Notes Alternate Name
Notes A placeholder property named @@iterator is used.
Alternate Name Uses the non-standard name: @@iterator
No support 17 — 27
Notes Alternate Name
Notes A placeholder property named iterator is used.
Alternate Name Uses the non-standard name: iterator
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 0.12
@@speciesChrome Full support 51Edge Full support 13Firefox Full support 41IE No support NoOpera Full support 38Safari Full support 10WebView Android Full support 51Chrome Android Full support 51Edge Mobile Full support 13Firefox Android Full support 41Opera Android Full support 38Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.5.0
Full support 6.5.0
Full support 6.0.0
Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.
@@toStringTagChrome Full support 44Edge No support NoFirefox Full support 51IE No support NoOpera No support NoSafari No support NoWebView Android Full support 44Chrome Android Full support 44Edge Mobile No support NoFirefox Android Full support 51Opera Android No support NoSafari iOS No support NoSamsung Internet Android Full support 4.0nodejs No support No

Legend

Full support  
Full support
Partial support  
Partial support
No support  
No support
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.
Uses a non-standard name.
Uses a non-standard name.

같이 보기

문서 태그 및 공헌자

이 페이지의 공헌자: mdnwebdocs-bot, alattalatta, KaironMoon, echo304, dragmove
최종 변경자: mdnwebdocs-bot,