A especificação do ECMAScript 6, embora ainda esteja em forma de rascunho, traz a promessa de muitas novas ferramentas interessantes para adicionar ao cinturão do programador JavaScript. Novas classes, como Set
e Map
, oferecem soluções nativas para trabalhar com tipos específicos de coleções, e a instrução for...of
oferece uma alternativa elegante às maneiras tradicionais de iterar dados.
Os Set
s oferecem uma maneira de acompanhar uma coleção de itens em que cada item pode aparecer no máximo uma vez. Os Map
s oferecem mais funcionalidade do que era possível anteriormente usando Object
s para associar chaves a valores. Com um Map
, as chaves não precisam ser strings, e você não precisa se preocupar em escolher acidentalmente um nome de chave que conflita com os nomes de método de um Object
. As operações de pesquisa em Map
s e Set
s nativos são realizadas em tempo constante, o que oferece ganhos de eficiência em relação ao que é possível com implementações simuladas.
O exemplo a seguir demonstra como construir um Set
e usar for...of
para iterar os elementos:
<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>
Confira um exemplo correspondente que ilustra o uso e a iteração de uma 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>
Alguns navegadores, como o Chrome, o Internet Explorer e o Firefox, já adicionaram suporte a Set
s e Map
s. O suporte nativo complementado por bibliotecas de polyfill, como es6-collections ou es6-shim, significa que os desenvolvedores de JavaScript podem começar a criar com esses novos tipos de coleção hoje mesmo. Não há polyfills disponíveis para a instrução for...of
, mas é possível transpilar o suporte pelo Traceur. No entanto, o suporte nativo está disponível no Chrome e no Firefox.
Atualização de setembro de 2014: vinculada a uma opção de polyfill adicional, es6-shim.