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