ES6 방식으로 수집 및 반복

ECMAScript 6 사양은 여전히 초안 형식이지만 JavaScript 프로그래머의 수준에 추가할 수 있는 새롭고 흥미로운 여러 도구를 제공합니다. SetMap와 같은 새로운 클래스는 특정 유형의 컬렉션으로 작업하는 네이티브 솔루션을 제공하며, for...of 문은 데이터를 반복하는 전통적인 방법에 대한 우아한 대안을 제공합니다.

Set는 각 항목이 최대 한 번 표시될 수 있는 항목 컬렉션을 추적하는 방법을 제공합니다. MapObject를 사용하여 키와 값을 연결하여 이전보다 더 많은 기능을 제공합니다. Map를 사용하면 키가 문자열일 필요가 없으며 실수로 Object의 메서드 이름과 충돌하는 키 이름을 선택할 필요가 없습니다. 네이티브 MapSet의 조회 작업은 일정 시간으로 실행되므로 시뮬레이션된 구현으로 가능한 작업보다 효율성이 향상됩니다.

다음 샘플에서는 Set를 구성하고 for...of를 사용하여 요소를 반복하는 방법을 보여줍니다.

<pre id="log"></pre>

<script>
    function log() {
    document.querySelector('#log').textContent += Array.prototype.join.call(arguments, '') + '\n';
    }

    log('Creating, using, and iterating over a Set:');
    var randomIntegers = new Set();
    // Generate a random integer in the range [1..10] five times,
    // and use a Set to keep track of the distinct integers that were generated.
    for (var i = 0; i < 5; i++) {
    randomIntegers.add(Math.floor(Math.random() * 10) + 1);
    }
    log(randomIntegers.size, ' distinct integers were generated.');
    log('The number 10 was ', randomIntegers.has(10) ? '' : 'not ', 'one of them.');
    log('Here\'s all of them:');
    // Use for...of to iterate over the items in the Set.
    // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iteration-statements
    // The Set iterator yields a single value corresponding to each entry in the Set.
    for (var item of randomIntegers) {
    log(item);
    }
</script>

다음은 Map 사용 및 반복을 보여주는 해당하는 샘플입니다.

<script>
    log('\nCreating and iterating over a Map:');
    // Maps can be initialized by passing in an iterable value (https://people.mozilla.org/~jorendorff/es6-draft.html#sec-map-iterable)
    // Here, we use an Array of Arrays to initialize. The first value in each sub-Array is the new
    // Map entry's key, and the second is the item's value.
    var typesOfKeys = new Map([
    ['one', 'My key is a string.'],
    ['1', 'My key is also a string'],
    [1, 'My key is a number'],
    [document.querySelector('#log'), 'My key is an object']
    ]);
    // You can also call set() to add new keys/values to an existing Map.
    typesOfKeys.set('!!!!', 'My key is excited!');

    // Use for...of to iterate over the items in the Map.
    // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iteration-statements
    // There are several types of Map iterators available.
    // typesOfKeys.keys() can be used to iterate over just the keys:
    log('Just the keys:');
    for (var key of typesOfKeys.keys()) {
    log('  key: ', key);
    }

    // typesOfKeys.values() can be used to iterate over just the values:
    log('Just the values:');
    for (var value of typesOfKeys.values()) {
    log('  value: ', value);
    }

    // The default Map iterator yields an Array with two items; the first is the Map entry's key and the
    // second is the Map entry's value. This default iterator is equivalent to typesOfKeys.entries().
    log('Keys and values:');
    // Alternative, ES6-idiomatic syntax currently supported in Safari & Firefox:
    // for (var [key, value] of typesOfKeys) { … }
    for (var item of typesOfKeys) {
    log('  ', item[0], ' -> ', item[1]);
    }
</script>

Chrome, Internet Explorer, Firefox와 같은 일부 브라우저에는 이미 SetMap에 대한 지원이 추가되었습니다. es6-collections 또는 es6-shim과 같은 polyfill 라이브러리로 기본 지원을 보완해 주므로 JavaScript 개발자가 지금 바로 이러한 새로운 컬렉션 유형으로 빌드를 시작할 수 있습니다. for...of 문에 사용할 수 있는 폴리필은 없지만 (Traceur를 통해 지원을 트랜스파일할 수 있음) 현재 ChromeFirefox에서 기본적으로 지원됩니다.

업데이트, 2014년 9월: 추가 polyfill 옵션인 es6-shim에 연결되었습니다.