الانتقال إلى المحتوى الرئيسي
eLearner.app
الوحدة 5 · الدرس 2 من 418/32 في الدورة~10 min
دروس الوحدة (2/4)

من أجل ... ومن أجل ... في

JavaScript has two "ergonomic" loops that should not be confused:

  • for…of iterates the values of an iterable collection (array, string, Set, Map...).
  • for…in iterates the enumerable keys of an object.

They are close cousins and easily swapped — using the wrong one is one of the language's first traps.

for…of for arrays and strings

JS
const colori = ['rosso', 'verde', 'blu'];
for (const c of colori) {
  console.log(c); // 'rosso', 'verde', 'blu'
}

for (const ch of 'abc') {
  console.log(ch); // 'a', 'b', 'c'
}

It does not give you the index. 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

JS
const utente = { nome: 'Anna', eta: 30, citta: 'Roma' };
for (const chiave in utente) {
  console.log(chiave, utente[chiave]); // 'nome' 'Anna', ...
}

When NOT to confuse them

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

// SBAGLIATO: stampa gli indici come stringhe!
for (const x in colori) {
  console.log(x); // '0', '1', '2'
}

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

Try it

تمرين#js.m5.l2.e1
المحاولات: 0جارٍ التحميل…

Define `concat(words)` that, given a list of strings, returns a string with all of them concatenated, separated by a space. Use for…of.

جارٍ تحميل المحرر…
إظهار التلميح

Accumulate into a string; add the space only if it is not the first word.

الحل متاح بعد 3 من المحاولات

Review exercise

تمرين#js.m5.l2.e2
المحاولات: 0جارٍ التحميل…

Define `positiveValues(obj)` that returns an array with the object's values that are numbers > 0. Use for…in. The order must match the iteration order of the keys.

جارٍ تحميل المحرر…
إظهار التلميح

Loop with for...in over the keys, filter with typeof and > 0, push into the results.

الحل متاح بعد 3 من المحاولات