JavaScript基本構文とDOM操作の実践

スクリプトの配置とコンソール出力

JavaScriptコードは通常、</body>タグの直前に記述します。これにより、ページのコンテンツが完全に読み込まれた後にスクリプトが実行されます。

開発中のデバッグにはconsole.log()を使用します。ブラウザの開発者ツール(右クリック → 検証)で確認できます。

<button id="actionBtn">実行</button>

<script>
  function executeAction() {
    console.log("ボタンがクリックされました");
  }
  
  document.getElementById("actionBtn").onclick = executeAction;
</script>

変数宣言のキーワード

JavaScriptは動的型付け言語です。同一変数に異なる型のデータを代入可能です。

  • let: ブロックスコープの変数。再代入可、再宣言不可。
  • const: 変更不可な定数。宣言時に初期化必須。
  • var: 関数スコープまたはグローバルスコープ。巻き上げ(hoisting)あり。
let userData = {};
const appName = "MyApp";
var isActive = true;

オブジェクトの動的操作

プロパティやメソッドを実行時に追加・削除できます。

userData.name = "山田太郎";
userData.greet = function() { return "こんにちは"; };
userData["age"] = 25;

// 動的プロパティ名
const key = "email";
userData[key] = "yamada@example.com";

// プロパティの削除
delete userData.age;

関数と引数処理

関数はファーストクラスオブジェクトとして扱われます。

const processInput = function(x, y) {
  console.log(`引数の数: ${arguments.length}`);
  console.log(`受け取った値: ${Array.from(arguments).join(", ")}`);
};

processInput("test");        // x="test", y=undefined
processInput(1, 2, 3, 4);   // argumentsで全引数にアクセス可能

型の判定方法

typeof演算子で基本型を判別します。

console.log(typeof "text");     // "string"
console.log(typeof 123);        // "number"
console.log(typeof {});         // "object"
console.log(typeof processInput); // "function"

配列操作の主要メソッド

メソッド説明
unshift(item)先頭に要素追加
push(item)末尾に要素追加
shift()先頭の要素削除
pop()末尾の要素削除
splice(start, deleteCount, items...)指定位置で削除・挿入
let numbers = [3, 4];
numbers.unshift(1, 2);           // [1,2,3,4]
numbers.push(5);                 // [1,2,3,4,5]
numbers.splice(2, 2, "a", "b");  // [1,2,"a","b",5]

DOM操作の基礎

Document Object Modelを通じてHTML要素を操作します。

// 要素の取得
const resultElement = document.getElementById("result");
const buttons = document.getElementsByClassName("btn");

// コンテンツの更新
resultElement.innerHTML = "<strong>成功</strong>";
resultElement.innerText = "プレーンテキスト";

タイマー機能

非同期処理に使用します。

let counter = 0;
const timerId = setInterval(() => {
  console.log(`カウント: ${++counter}`);
}, 200);

// 2秒後に停止
setTimeout(() => {
  clearInterval(timerId);
  console.log("タイマー終了");
}, 2000);

実践例:抽選アプリケーション

ユーザー入力に基づいたランダム抽選システムの実装。

const drawSystem = {
  pool: [],
  isRunning: false,
  maxNumber: 0,

  initialize(max) {
    this.maxNumber = max;
    this.pool = Array.from({length: max}, (_, i) => i + 1);
    this.isRunning = true;
  },

  drawRandom() {
    if (this.pool.length === 0) {
      alert("すべての番号が抽選済みです");
      return null;
    }

    const index = Math.floor(Math.random() * this.pool.length);
    return this.pool.splice(index, 1)[0];
  }
};

// UI連携
document.getElementById("drawBtn").addEventListener("click", function() {
  const input = document.getElementById("maxInput");
  const max = parseInt(input.value);

  if (!drawSystem.isRunning) {
    drawSystem.initialize(max);
    input.disabled = true;
  }

  // アニメーション効果
  const interval = setInterval(() => {
    const temp = Math.floor(Math.random() * drawSystem.maxNumber) + 1;
    document.getElementById("display").textContent = temp;
  }, 50);

  setTimeout(() => {
    clearInterval(interval);
    const result = drawSystem.drawRandom();
    if (result !== null) {
      document.getElementById("display").textContent = result;
      const history = document.getElementById("history");
      const badge = document.createElement("span");
      badge.textContent = result;
      badge.style.margin = "2px";
      badge.style.padding = "4px 8px";
      badge.style.backgroundColor = "#3EAFE0";
      badge.style.color = "white";
      badge.style.borderRadius = "3px";
      history.appendChild(badge);
    } else {
      input.disabled = false;
    }
  }, 1000);
});

タグ: javascript DOM操作 変数宣言 配列操作 タイマー

7月25日 20:46 投稿