ECMAScript 6 规范仍为草稿形式,带来了许多令人兴奋的新工具,可供 JavaScript 编程人员轻松使用。Set
和 Map
等新类提供了处理特定类型的集合的原生解决方案,for...of
语句为传统的数据迭代方法提供了完美的替代方案。
Set
提供了一种跟踪一系列项的方法,其中每项项最多可以出现一次。与以前相比,Map
提供了更多功能,它们使用 Object
将键与值相关联。使用 Map
,您的键不必是字符串,而且您不必担心意外选择的键名与 Object
的方法名称冲突。对原生 Map
和 Set
的查找操作是在恒定时间内完成的,与模拟实现相比,这种方法的效率更高。
以下示例演示了如何构建 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)已经添加了对 Set
和 Map
的支持。原生支持与 es6-collections 或 es6-shim 等 polyfill 库相辅相成,这意味着 JavaScript 开发者可以立即开始使用这些新的集合类型进行构建。没有适用于 for...of
语句的 polyfill(尽管可以通过 Traceur 转译支持),但目前 Chrome 和 Firefox 中提供了原生支持。
更新,2014 年 9 月:链接到了一个额外的 polyfill 选项 es6-shim