मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 5 · पाठ 2 का 4पाठ्यक्रम में 18/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 प्रयासों के बाद समाधान उपलब्ध है