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"을 참고하세요.
Object와 Map 비교
Object는 값에 키를 할당할 수 있고, 그 키로 값을 얻을 수 있고, 키를 삭제할 수 있으며 어떤 키에 값이 존재하는지 확인할 수 있다는 점에서 Maps와 유사합니다. 이러한 이유와, 내장 대체제가 없었기 때문에 역사적으로 Object를 Map 대신 사용하곤 했습니다. 그러나 어떤 상황에선 Map을 고려해야 할 몇 가지 중요한 차이점이 있습니다.
Object의 키에는String과Symbol을 사용할 수 있지만,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.prototypeMap생성자의 프로토타입을 나타냅니다. 모든Map인스턴스에 속성을 추가할 수 있습니다.
Map 인스턴스
모든 Map 인스턴스는 Map.prototype을 상속받습니다.
속성
Map.prototype.constructor- 인스턴스의 프로토타입을 만드는 함수를 반환한다. 이것
Map함수의 기본 값이다. Map.prototype.sizeMap객체에 들어있는 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..of로 Map 순회하기
Map은 for..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 순회하기
Map은 forEach() 메서드로 순회할 수 있습니다.
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 |
브라우저 호환성
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Map | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs
Full support
0.12
|
new Map(iterable) | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE No support No | Opera Full support 25 | Safari Full support 9 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 9 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
new Map(null) | Chrome Full support Yes | Edge Full support 12 | Firefox Full support 37 | IE Full support 11 | Opera Full support Yes | Safari Full support 9 | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support 12 | Firefox Android Full support 37 | Opera Android Full support Yes | Safari iOS Full support 9 | Samsung Internet Android Full support Yes | nodejs
Full support
0.12
|
Map() without new throws | Chrome Full support Yes | Edge Full support 12 | Firefox Full support 42 | IE Full support 11 | Opera Full support Yes | Safari Full support 9 | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support 12 | Firefox Android Full support 42 | Opera Android Full support Yes | Safari iOS Full support 9 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
| Key equality for -0 and 0 | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 29 | IE No support No | Opera Full support 25 | Safari Full support 9 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 29 | Opera Android Full support 25 | Safari iOS Full support 9 | Samsung Internet Android Full support Yes | nodejs Full support 4.0.0 |
clear | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 19 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 19 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
delete | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs
Full support
0.12
|
entries | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 20 | IE No support No | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 20 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
forEach | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 25 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 25 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
get | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support Yes |
has | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support Yes |
keys | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 20 | IE No support No | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 20 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
prototype | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support Yes |
set | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 13 | IE
Partial support
11
| Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 14 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support Yes |
size | Chrome Full support 38 | Edge Full support 12 | Firefox
Full support
19
| IE Full support 11 | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android
Full support
19
| Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
values | Chrome Full support 38 | Edge Full support 12 | Firefox Full support 20 | IE No support No | Opera Full support 25 | Safari Full support 8 | WebView Android Full support 38 | Chrome Android Full support 38 | Edge Mobile Full support 12 | Firefox Android Full support 20 | Opera Android Full support 25 | Safari iOS Full support 8 | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
@@iterator | Chrome Full support Yes | Edge Full support Yes | Firefox
Full support
36
| IE No support No | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support Yes | Firefox Android
Full support
36
| Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
@@species | Chrome Full support 51 | Edge Full support 13 | Firefox Full support 41 | IE No support No | Opera Full support 38 | Safari Full support 10 | WebView Android Full support 51 | Chrome Android Full support 51 | Edge Mobile Full support 13 | Firefox Android Full support 41 | Opera Android Full support 38 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs
Full support
6.5.0
|
@@toStringTag | Chrome Full support 44 | Edge No support No | Firefox Full support 51 | IE No support No | Opera No support No | Safari No support No | WebView Android Full support 44 | Chrome Android Full support 44 | Edge Mobile No support No | Firefox Android Full support 51 | Opera Android No support No | Safari iOS No support No | Samsung Internet Android Full support 4.0 | nodejs 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.