Chuyển đến nội dung chính
eLearner.app
Mô-đun 3 · Bài học 4 trong tổng số 412/32 trong khóa học~10 min
Bài học theo mô-đun (4/4)

Lặp lại các bộ sưu tập

Manipulating collections almost always means iterating: walking through the elements one at a time and doing something for each. In this lesson we look at the basic syntaxes; in the functional arrays module (map / filter / reduce) we'll learn to write them more declaratively.

for…of for arrays

It's the loop you'll want to use almost always to iterate an array: it extracts the value at every step.

JS
const colori = ['rosso', 'verde', 'blu'];

for (const c of colori) {
  console.log(c);
}
// 'rosso'
// 'verde'
// 'blu'

If you also need the index, use entries():

JS
for (const [i, c] of colori.entries()) {
  console.log(`${i}: ${c}`);
}
// '0: rosso', '1: verde', '2: blu'

for…in for objects — with caution

for…in iterates the keys (strings) of an object:

JS
const utente = { nome: 'Anna', eta: 28 };
for (const k in utente) {
  console.log(`${k} = ${utente[k]}`);
}

Object.keys / values / entries

These are the robust way to iterate an object. They return arrays, and so they combine very well with for…of:

JS
const utente = { nome: 'Anna', eta: 28 };

Object.keys(utente); // ['nome', 'eta']
Object.values(utente); // ['Anna', 28]
Object.entries(utente); // [['nome', 'Anna'], ['eta', 28]]

for (const [k, v] of Object.entries(utente)) {
  console.log(`${k} → ${v}`);
}

Classic for

The "old-school" for still exists. You'll use it rarely, but it's useful when you need fine control over the index (skipping elements, iterating backwards):

JS
for (let i = 0; i < colori.length; i++) {
  console.log(i, colori[i]);
}

// Backwards
for (let i = colori.length - 1; i >= 0; i--) {
  console.log(colori[i]);
}

Try it

tập thể dục#js.m3.l4.e1
Nỗ lực: 0Đang tải…

Given `numbers = [3, 5, 7]`, compute the sum of all elements (15) by iterating with for...of. The last expression must evaluate to the sum.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

for (const n of numbers) { sum = sum + n; }

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#js.m3.l4.e2
Nỗ lực: 0Đang tải…

Given `prices = { mela: 0.4, pera: 0.55, banana: 0.3 }`, return the TOTAL NUMBER of entries in the object (3) using Object.keys.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Object.keys(obj) returns an array; .length tells how many keys there are.

Giải pháp khả dụng sau 3 lần thử