JavaScript | JavaScript 演算子の優先順位 一覧表(初心者向け)

javascrpit JavaScript
スポンサーリンク

左結合・右結合 実験デモ(HTML+JS)

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>左結合 vs 右結合 実験デモ</title>
<style>
  body {
    font-family: "Segoe UI", sans-serif;
    background: #f7f9fc;
    color: #333;
    padding: 20px;
    text-align: center;
  }
  input, button {
    font-size: 1rem;
    padding: 8px;
    margin: 8px;
  }
  #steps {
    margin-top: 20px;
    text-align: left;
    max-width: 600px;
    margin-inline: auto;
  }
  .highlight {
    background: #ffeaa7;
    padding: 2px 6px;
    border-radius: 6px;
  }
</style>
</head>
<body>

<h1>⚖️ 左結合 vs 右結合 実験デモ</h1>
<p>例:<code>10 - 3 - 2</code>(左結合)や <code>2 ** 3 ** 2</code>(右結合)を試してみよう!</p>

<input id="expr" type="text" value="10 - 3 - 2">
<button id="run">実行</button>

<div id="steps"></div>

<script>
document.getElementById("run").addEventListener("click", () => {
  const expr = document.getElementById("expr").value.trim();
  const stepsDiv = document.getElementById("steps");
  stepsDiv.innerHTML = "";

  try {
    // 安全に評価するため new Function を使用
    const result = new Function(`return (${expr});`)();
    let explanation = "";

    if (expr.includes("-")) {
      explanation = `
        <p>この式は <strong>左結合</strong> です。</p>
        <p>演算順序:</p>
        <p><code>(10 - 3) - 2</code> → <code>7 - 2</code> → <strong>5</strong></p>`;
    } else if (expr.includes("**")) {
      explanation = `
        <p>この式は <strong>右結合</strong> です。</p>
        <p>演算順序:</p>
        <p><code>2 ** (3 ** 2)</code> → <code>2 ** 9</code> → <strong>512</strong></p>`;
    } else if (expr.includes("=")) {
      explanation = `
        <p>代入演算子は <strong>右結合</strong> です。</p>
        <p>例:<code>a = b = 3</code> は <code>a = (b = 3)</code> の順で処理されます。</p>`;
    } else {
      explanation = `<p>この式の演算子の結合性はケースによって異なります。</p>`;
    }

    stepsDiv.innerHTML = `
      <h2>🧩 結果:${result}</h2>
      <div class="highlight">${explanation}</div>`;
  } catch (e) {
    stepsDiv.innerHTML = `<p style="color:red;">式の解析に失敗しました。</p>`;
  }
});
</script>

</body>
</html>
HTML

このデモで学べること

項目内容
左結合(Left-associative)左から順に評価。例:10 - 3 - 2(10 - 3) - 2
右結合(Right-associative)右から順に評価。例:2 ** 3 ** 22 ** (3 ** 2)
代表例左結合:+, -, *, / / 右結合:=, **, ?:
ポイント結合方向を誤解すると計算結果が変わる!
タイトルとURLをコピーしました