問題一覧に戻る
中級es6
問題79: for...in ループ
for...inループを学びましょう。この構文はオブジェクトの列挙可能なプロパティ名(キー)を反復処理します。オブジェクトの全プロパティを処理したい場合や、動的なプロパティアクセスが必要な場合に便利です。ただし、プロトタイプチェーン上のプロパティも列挙されるため、必要に応じてhasOwnPropertyでのチェックが重要です。配列に対してはfor...ofを使うことが推奨されますが、オブジェクトのプロパティ処理には現在も有用な構文です。
// for...inループ
const person = {
name: "太郎",
age: 25,
city: "東京"
};
// オブジェクトの反復
let props = [];
for (const key person) {
props.push(key + ":" + person[]);
}
console.log("プロパティ: " + props.join(","));
// 文字列の構築
const scores = {
math: 90,
english: 85,
science: 95,
history: 80,
art: 50
};
let total = 0;
for (const subject scores) {
total += scores[subject];
}
console.log("値の合計: " + total);