for of mdn code example

Example 1: for of mdn

let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let entry of iterable) {
  console.log(entry);
}
// [a, 1]
// [b, 2]
// [c, 3]

for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3

Example 2: for of mdn

Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};

let iterable = [3, 5, 7];
iterable.foo = "hello";

for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}

for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

Example 3: for of mdn

let iterable = new Uint8Array([0x00, 0xff]);

for (let value of iterable) {
  console.log(value);
}
// 0
// 255

Example 4: for of mdn

function* fibonacci() { // generatore di funzione
  let [prev, curr] = [0, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
  }
}

for (let n of fibonacci()) {
  console.log(n);
  // tronca la sequenza a 1000
  if (n >= 1000) {
    break;
  }
}

Example 5: for of mdn

let iterable = "boo";

for (let value of iterable) {
  console.log(value);
}
// output:
// "b"
// "o"
// "o"

Example 6: for of mdn

let iterable = [10, 20, 30];

for (const value of iterable) {
  console.log(value); // il valore di value di questo ciclo rimarrà costante
  value++; // operazione non consentita.
}
// 10
// 20
// 30

Example 7: for of mdn

let iterable = new Set([1, 1, 2, 2, 3, 3]);

for (let value of iterable) {
  console.log(value);
}
// 1
// 2
// 3

Example 8: for of mdn

let array = [10, 20, 30];

for (let valore of array) {
  console.log(valore);
}
// Output:
// 10
// 20
// 30

Example 9: for of mdn

for (variabile of oggettoIterabile) {
  istruzioni
}

Tags:

Misc Example