コンテンツへスキップ

Looping over objects

English

Visit every key of an object

  • An object has no index 0, 1, 2, so a plain for loop cannot walk through it.
  • for (const key in obj) gives you each key in turn.
  • Read the value with square brackets: obj[key]. The dot form, obj.key, would look for a key literally called "key".

for (const fruit in stock) visits apples, pears and plums in turn; stock[fruit] reads 4, 0 and 7

プリント

ログインまたはアカウント作成

IGCSE, A-Level & AP