收集和迭代(ES6 方式)

ECMAScript 6 规范虽然仍处于草稿形式,但有望为 JavaScript 程序员提供许多令人兴奋的新工具。SetMap 等新类提供了处理特定类型集合的原生解决方案,for...of 语句则提供了一种优雅的替代方案,可用于迭代数据的传统方法。

Set 提供了一种跟踪一组项的方法,其中每个项最多只能出现一次。Map 提供了比之前使用 Object 将键与值相关联时更多的功能。使用 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>

某些浏览器(例如 ChromeInternet ExplorerFirefox)已添加对 SetMap 的支持。借助原生支持和 es6-collectionses6-shim 等 polyfill 库,JavaScript 开发者现在就可以开始使用这些新集合类型进行构建。目前没有适用于 for...of 语句的 polyfill(不过可以通过 Traceur 转译支持),但 ChromeFirefox 目前提供原生支持。

更新(2014 年 9 月):关联到其他 polyfill 选项 es6-shim