では次のステップとして、「さらにネストした配列+オブジェクト(学校→クラス→生徒→科目点数)の複合更新ステップ実行」を紹介します。
練習問題:学校データの複合更新
let school = [
{
className: "1年A組",
students: [
{
name: "Alice",
scores: { math: 95, english: 88 },
passed: false,
honors: false
},
{
name: "Bob",
scores: { math: 62, english: 70 },
passed: false,
honors: false
}
]
},
{
className: "1年B組",
students: [
{
name: "Charlie",
scores: { math: 78, english: 85 },
passed: false,
honors: false
},
{
name: "David",
scores: { math: 55, english: 60 },
passed: false,
honors: false
}
]
}
];
// 複合条件で passed と honors を更新
for (let i = 0; i < school.length; i++) {
let classroom = school[i];
for (let j = 0; j < classroom.students.length; j++) {
let student = classroom.students[j];
let avg = (student.scores.math + student.scores.english) / 2;
if (avg >= 70) {
student.passed = true;
if (avg >= 90) {
student.honors = true;
}
} else {
student.passed = false;
student.honors = false;
}
}
}
console.log(school);
JavaScript出力(抜粋)
[
{
className: "1年A組",
students: [
{ name: "Alice", scores: { math: 95, english: 88 }, passed: true, honors: true },
{ name: "Bob", scores: { math: 62, english: 70 }, passed: true, honors: false }
]
},
{
className: "1年B組",
students: [
{ name: "Charlie", scores: { math: 78, english: 85 }, passed: true, honors: false },
{ name: "David", scores: { math: 55, english: 60 }, passed: false, honors: false }
]
}
]
JavaScriptステップ実行(逐次追跡)
| i | j | 学生 | math | english | avg | 条件評価 | passed | honors |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 | Alice | 95 | 88 | 91.5 | avg>=70 → true, avg>=90 → true | true | true |
| 0 | 1 | Bob | 62 | 70 | 66 | avg>=70 → false | false | false |
| 1 | 0 | Charlie | 78 | 85 | 81.5 | avg>=70 → true, avg>=90 → false | true | false |
| 1 | 1 | David | 55 | 60 | 57.5 | avg>=70 → false | false | false |
解説ポイント
- 三重構造
- 外側
for (i)→ クラス - 中間
for (j)→ 学生 - 内側のオブジェクト
scores→ 科目点数
- 外側
- 複合条件
- 平均点 >= 70 → 合格
- 平均点 >= 90 → 名誉賞
- 逐次追跡表での利点
- 各学生の点数・平均・条件評価・更新プロパティを明確に確認できる
- 参照型
studentの更新はschool配列に直接反映
💡 このパターンは実務で非常に頻出です:
- 成績管理、売上データ、ユーザーアクティビティ集計など
- ネスト構造の条件分岐とプロパティ更新を組み合わせた処理


