Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

for...of

This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

Resum

La instrucció for...of crea un bucle que itera sobre objectes iterables (incloent ArrayMap, Set, l'objecte arguments, etcètera), tot invocant un bloc de codi amb les instruccions a executar per a cada valor de la propietat.

Sintaxi

for (variable of objecte)
  codi
variable
A cada iteració el valor d'una propietat diferent és asignat a variable.
objecte
L'objecte del qual s'iteren les propietats, que són iterables.

Exemples

Diferència entre for...of i for...in

El següent exemple mostra la diferència entre el bucle for...of i el bucle for...in. Mentre for...in itera sobre noms de propietats, for...of itera sobre els valors de les propietats:

let arr = [3, 5, 7];
arr.foo = "hola";

for (let i in arr) {
   console.log(i); // mostra "0", "1", "2", "foo"
}

for (let i of arr) {
   console.log(i); // mostra "3", "5", "7"
}

Ús de Array.prototype.forEach()

Per a aconseguir els mateixos valors que s'obtenen amb for...of també es pot utilitzar el mètode Array.prototype.forEach():

let arr = [3, 5, 7];
arr.foo = "hola";

arr.forEach(function (element, index) {
    console.log(element); // mostra "3", "5", "7"
    console.log(index);   // mostra "0", "1", "2"
});

// or with Object.keys()

Object.keys(arr).forEach(function (element, index) {
    console.log(arr[element]); // mostra "3", "5", "7", "hello"
    console.log(arr[index]);   // mostra "3", "5", "7"
});

Iteració de coleccions del DOM

Iterant sobre coleccions del DOM com NodeList: el següent exemple afegeix la classe read als paràgrafs que són descendens directes d'un article:

// Nota: Això només funcionarà en plataformes que
// implementen NodeList.prototype[Symbol.iterator]
let articleParagraphs = document.querySelectorAll("article > p");

for (let paragraph of articleParagraphs) {
  paragraph.classList.add("read");
}

Iteració de generadors:

Els generadors també són iterables:

function* fibonacci() { // una funció generadora
    let [prev, curr] = [0, 1];
    for (;;) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

for (let n of fibonacci()) {
    // trunca la seqüència als 1000
    if (n > 1000)
        break;
    print(n);
}

Especificacions

Especificació Estat Comentari
ECMAScript 6 (ECMA-262)
The definition of 'for...of statement' in that specification.
Release Candidate Definició inicial.

Compatibilitat amb navegadors

Característica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suport bàsic 29[1]
38
13 (13)
17 (17) (.iterator)
27 (27) ("@@iterator")
36 (36) (Symbol.iterator)
Not supported 25 7.1
Característica Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suport bàsic ? 29[1]
38
13.0 (13)
17.0 (17) (.iterator)
27.0 (27) ("@@iterator")
36.0 (36) (Symbol.iterator)
? ? iOS 8

[1] La característica està disponible sota una preferència. A chrome://flags/#enable-javascript-harmony, activar la entrada “Enable Experimental JavaScript”.

Vegeu també

Document Tags and Contributors

 Contributors to this page: fscholz, enTropy
 Last updated by: fscholz,