ECMAScript 6 仕様は、まだドラフト形式ですが、JavaScript プログラマのツールボックスに追加できる、エキサイティングな新しいツールが数多く含まれています。Set
や Map
などの新しいクラスは、特定のタイプのコレクションを操作するためのネイティブ ソリューションを提供します。また、for...of
ステートメントは、従来のデータの反復処理方法に代わるエレガントな方法を提供します。
Set
は、各アイテムが最大 1 回しか出現しないアイテムのコレクションを追跡する方法を提供します。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 などのポリフィル ライブラリを組み合わせることで、JavaScript デベロッパーは、これらの新しいコレクション タイプを使用してすぐに開発を開始できます。for...of
ステートメントに使用できるポリフィルはありません(ただし、Traceur を介してサポートをトランスパイルすることは可能です)。ただし、現在、Chrome と Firefox ではネイティブ サポートが利用可能です。
更新(2014 年 9 月): 追加のポリフィル オプション es6-shim にリンクされました