Thu thập và lặp lại, cách ES6

Mặc dù vẫn ở dạng bản nháp, nhưng thông số kỹ thuật ECMAScript 6 hứa hẹn sẽ mang đến nhiều công cụ mới thú vị để bổ sung vào bộ công cụ của lập trình viên JavaScript. Các lớp mới như SetMap cung cấp các giải pháp gốc để xử lý các loại bộ sưu tập cụ thể, đồng thời câu lệnh for...of cung cấp một giải pháp thay thế thanh lịch cho các phương pháp lặp lại dữ liệu truyền thống.

Set cung cấp một cách để theo dõi một tập hợp các mục, trong đó mỗi mục có thể xuất hiện tối đa một lần. Map cung cấp nhiều chức năng hơn so với trước đây bằng cách sử dụng Object để liên kết khoá với giá trị. Với Map, khoá của bạn không nhất thiết phải là chuỗi và bạn không phải lo lắng về việc vô tình chọn tên khoá xung đột với tên phương thức của Object. Các thao tác tra cứu trên MapSet gốc được thực hiện trong thời gian không đổi, giúp tăng hiệu quả so với những gì có thể thực hiện được với các phương thức triển khai mô phỏng.

Mẫu sau minh hoạ cách tạo Set và sử dụng for...of để lặp lại các phần tử của Set:

<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>

Sau đây là mẫu tương ứng minh hoạ cách sử dụng và lặp lại trên 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>

Một số trình duyệt như Chrome, Internet ExplorerFirefox đã thêm tính năng hỗ trợ cho SetMap. Tính năng hỗ trợ gốc được bổ sung bằng các thư viện polyfill như es6-collections hoặc es6-shim có nghĩa là các nhà phát triển JavaScript có thể bắt đầu xây dựng bằng các loại bộ sưu tập mới này ngay hôm nay. Không có polyfill nào cho câu lệnh for...of (mặc dù có thể chuyển đổi tính năng hỗ trợ thông qua Traceur), nhưng hiện tại, tính năng hỗ trợ gốc có trong ChromeFirefox.

Nội dung cập nhật, tháng 9 năm 2014: Được liên kết với một tuỳ chọn polyfill bổ sung, es6-shim