let array = [10, 20, 30];
for (let valore of array) {
console.log(valore);
}
// Output:
// 10
// 20
// 30
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;
}
}
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
let iterable = "boo";
for (let value of iterable) {
console.log(value);
}
// output:
// "b"
// "o"
// "o"
let iterable = new Uint8Array([0x00, 0xff]);
for (let value of iterable) {
console.log(value);
}
// 0
// 255
let iterable = new Set([1, 1, 2, 2, 3, 3]);
for (let value of iterable) {
console.log(value);
}
// 1
// 2
// 3
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
}
function* fibonacci() { // a generator function
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (const n of fibonacci()) {
console.log(n);
// truncate the sequence at 1000
if (n >= 1000) {
break;
}
}