JavaScript | レベル別練習問題:オブジェクト

JavaScript
スポンサーリンク

では「オブジェクト操作」を題材にしたステップ実行解説を紹介します。
変数・オブジェクトの状態が逐次追跡できるように、表形式で分かりやすく解説します。


練習問題:オブジェクトのプロパティ操作

let user = {
    name: "Alice",
    age: 25,
    active: false
};

// 年齢によって active 状態を更新
if (user.age >= 18) {
    user.active = true;
}

// 名前を表示用に加工
let displayName = user.name.toUpperCase();

console.log(displayName, user.active);
JavaScript

出力

ALICE true

ステップ実行(逐次追跡)

ステップ処理user.nameuser.ageuser.activedisplayName条件評価実行ブロック
let user = {...} 初期化“Alice”25false“”オブジェクト作成
if (user.age >= 18) 評価“Alice”25false“”trueuser.active = true
プロパティ更新後“Alice”25true“”
displayName = user.name.toUpperCase() 実行“Alice”25true“ALICE”displayName に代入
console.log(displayName, user.active) 実行“Alice”25true“ALICE”出力: “ALICE true”

解説ポイント

  1. オブジェクトのプロパティ変更は参照を通じて行われる
    • user.active = true はオブジェクト自体を直接更新
  2. 変数 displayName は文字列操作の結果を別変数に代入
    • 元のオブジェクトには影響なし
  3. 条件分岐を使ってオブジェクトの状態を制御
    • ネスト条件や複数プロパティでも同じ要領で追跡可能

応用例:オブジェクト内の複数条件で更新

let user = {
    name: "Bob",
    age: 16,
    hasParentalConsent: true,
    active: false
};

if (user.age >= 18 || user.hasParentalConsent) {
    user.active = true;
}

let displayName = user.name.toUpperCase();
console.log(displayName, user.active);
JavaScript

出力

BOB true

ステップ実行

ステップ処理user.nameuser.ageuser.hasParentalConsentuser.activedisplayName条件評価実行ブロック
オブジェクト初期化“Bob”16truefalse“”
`if (user.age >= 18user.hasParentalConsent)` 評価“Bob”16truefalse“”
プロパティ更新後“Bob”16truetrue“”
displayName = user.name.toUpperCase() 実行“Bob”16truetrue“BOB”displayName に代入
console.log(displayName, user.active) 実行“Bob”16truetrue“BOB”出力: “BOB true”

ポイントまとめ

  • オブジェクトは参照型:プロパティ更新は元のオブジェクトに反映される
  • 条件分岐で複数プロパティを組み合わせて更新可能
  • 逐次表にすると「どの条件が評価されたか」「どのプロパティが変更されたか」が一目でわかる
  • ネスト条件や論理演算子を追加しても、同じステップ表で追跡できる
タイトルとURLをコピーしました