Pętle
Pętla for
Jedną z najczęściej stosowanych pętli jest instrukcja for.
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
console.log(arr[i][j]);
}
}
Ilość elementów możemy określić wewnątrz instrukcji, np:
for (let i = 0, l = arr.length; i < l; i++) {
// …
}
Pętla while
Struktura tej pętli jest następująca:
const colors = [‘red’, ‘white’, ‘blue’];
let i = 0;
while (i < colors.length) {
console.log(colors[i]);
i++;
}
Pętla for… of
Kolejny rodzaj pętli:
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
for (row of arr) {
for (num of row) {
console.log(num)
}
}
Iterować możemy po każdym iterowalnym obiekcie, w tym po łańcuchach znaków:
for (let char of ‘respect’) {
console.log(char.toUpperCase());
}
Wraz z Object.keys
umożliwia również iterację po obiektach:
const movies = {
Terminator: 9.8,
Matrix: 9.8,
‘Pulp Fiction’: 9.8,
};
for (let movie of Object.keys(movies)) {
console.log(‘${movie}: ${movies[movie]}‘);
}
Pętla for… in
Iteruje po obiekcie i zwraca jego klucze:
const movies = {
Terminator: 9.8,
Matrix: 9.8,
‘Pulp Fiction’: 9.8,
};
for (let movie in movies) {
console.log(movie); // Terminator Matrix Pulp Fiction
}
Możemy uzyskać dostęp również do wartości:
for (let movie in movies) {
console.log(movie); // Terminator Matrix Pulp Fiction
console.log(movies[movie]); // 9.8 9.8 9.8
}