1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

新・JavaScript文法(9):組み込みオブジェクトとユーティリティ

Last updated at Posted at 2025-07-03

前回の記事 では、JavaScriptのクラス構文とオブジェクト指向プログラミングについて、従来のプロトタイプベースのアプローチとの違いを含めて紹介しました。今回は、JavaScriptの組み込みオブジェクトとユーティリティ機能について、よく使用される便利なメソッドや機能を中心に紹介します。

String(文字列)オブジェクトの便利なメソッド

最初に扱うのは、文字列を操作するためのメソッドです。

よく使用される文字列メソッド

const text = "Hello, JavaScript World!";

// includes() - 文字列に指定した文字列が含まれているかを確認
console.log(text.includes("JavaScript")); // true
console.log(text.includes("Python")); // false

// repeat() - 文字列を指定した回数繰り返す
console.log("*".repeat(5)); // "*****"
console.log("Hello ".repeat(3)); // "Hello Hello Hello "

// startsWith() / endsWith() - 文字列の開始/終了を確認
console.log(text.startsWith("Hello")); // true
console.log(text.endsWith("World!")); // true

// padStart() / padEnd() - 文字列を指定した長さまで埋める
const num = "42";
console.log(num.padStart(5, "0")); // "00042"
console.log(num.padEnd(5, "0")); // "42000"

文字列の検索と置換

const message = "JavaScriptは楽しい言語です。JavaScriptを学びましょう。";

// indexOf() / lastIndexOf() - 文字列の位置を取得
console.log(message.indexOf("JavaScript")); // 0
console.log(message.lastIndexOf("JavaScript")); // 17

// replace() / replaceAll() - 文字列の置換
console.log(message.replace("JavaScript", "JS")); // 最初の1つだけ置換
console.log(message.replaceAll("JavaScript", "JS")); // すべて置換

// 正規表現を使った置換
const phoneNumber = "090-1234-5678";
const formatted = phoneNumber.replace(/-/g, "");
console.log(formatted); // "09012345678"

Array(配列)オブジェクトのモダンなメソッド

ES2015以降で追加された配列メソッドは、データの検索や条件判定を行なうことができます。

検索とフィルタリング

const products = [
  { id: 1, name: "ノートPC", price: 85000, category: "electronics" },
  { id: 2, name: "デスク", price: 25000, category: "furniture" },
  { id: 3, name: "イヤホン", price: 15000, category: "electronics" },
  { id: 4, name: "椅子", price: 30000, category: "furniture" }
];

// find() - 条件に一致する最初の要素を取得
const laptop = products.find(product => product.name === "ノートPC");
console.log(laptop); // { id: 1, name: "ノートPC", price: 85000, category: "electronics" }

// findIndex() - 条件に一致する最初の要素のインデックスを取得
const laptopIndex = products.findIndex(product => product.name === "ノートPC");
console.log(laptopIndex); // 0

// filter() - 条件に一致するすべての要素を取得
const electronics = products.filter(product => product.category === "electronics");
console.log(electronics.length); // 2

条件判定

const numbers = [2, 4, 6, 8, 10];
const mixedNumbers = [1, 2, 3, 4, 5];

// every() - すべての要素が条件を満たすかを判定
console.log(numbers.every(num => num % 2 === 0)); // true(すべて偶数)
console.log(mixedNumbers.every(num => num % 2 === 0)); // false

// some() - 少なくとも一つの要素が条件を満たすかを判定
console.log(numbers.some(num => num > 5)); // true(5より大きい数がある)
console.log(mixedNumbers.some(num => num > 10)); // false

// includes() - 指定した値が配列に含まれるかを判定
console.log(numbers.includes(4)); // true
console.log(numbers.includes(3)); // false

Math(数学)オブジェクト

数学的な計算や値の処理に使用されるメソッドと定数を紹介します。

よく使用される数学メソッド

// 基本的な数学メソッド
console.log(Math.floor(4.7)); // 4(小数点切り捨て)
console.log(Math.ceil(4.1)); // 5(小数点切り上げ)
console.log(Math.round(4.5)); // 5(四捨五入)
console.log(Math.trunc(4.9)); // 4(整数部分のみ取得)

// 最大値・最小値
console.log(Math.max(10, 5, 8, 3)); // 10
console.log(Math.min(10, 5, 8, 3)); // 3

// 配列の最大値・最小値(スプレッド構文と組み合わせ)
const scores = [85, 92, 78, 96, 88];
console.log(Math.max(...scores)); // 96
console.log(Math.min(...scores)); // 78

// 絶対値とべき乗
console.log(Math.abs(-42)); // 42
console.log(Math.pow(2, 3)); // 8(2の3乗)
console.log(2 ** 3); // 8(ES2016以降のべき乗演算子)

// ランダム値の生成
console.log(Math.random()); // 0以上1未満のランダムな数値
console.log(Math.floor(Math.random() * 10) + 1); // 1〜10のランダムな整数

実用的な数学計算

// 範囲内のランダムな整数を生成する関数
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandomInt(1, 100)); // 1〜100のランダムな整数

// 数値を指定した桁数で丸める関数
function roundToDecimals(number, decimals) {
  const factor = Math.pow(10, decimals);
  return Math.round(number * factor) / factor;
}

console.log(roundToDecimals(3.14159, 2)); // 3.14
console.log(roundToDecimals(2.675, 2)); // 2.68

JSON操作

JSON(JavaScript Object Notation)は、広く使用されているデータ形式です。

基本的なJSON操作

// オブジェクトをJSON文字列に変換
const user = {
  id: 1,
  name: "田中太郎",
  email: "tanaka@example.com",
  skills: ["JavaScript", "HTML", "CSS"]
};

const jsonString = JSON.stringify(user);
console.log(jsonString);
// {"id":1,"name":"田中太郎","email":"tanaka@example.com","skills":["JavaScript","HTML","CSS"]}

// JSON文字列をオブジェクトに変換
const parsedUser = JSON.parse(jsonString);
console.log(parsedUser.name); // "田中太郎"
console.log(parsedUser.skills); // ["JavaScript", "HTML", "CSS"]

JSON操作の実践例

// ローカルストレージへのデータ保存
function saveUserData(userData) {
  try {
    const jsonData = JSON.stringify(userData);
    localStorage.setItem('userData', jsonData);
    console.log('データを保存しました');
  } catch (error) {
    console.error('データの保存に失敗しました:', error);
  }
}

// ローカルストレージからのデータ読み込み
function loadUserData() {
  try {
    const jsonData = localStorage.getItem('userData');
    if (jsonData) {
      return JSON.parse(jsonData);
    }
    return null;
  } catch (error) {
    console.error('データの読み込みに失敗しました:', error);
    return null;
  }
}

// APIレスポンスの処理(疑似的な例)
function processApiResponse(responseText) {
  try {
    const data = JSON.parse(responseText);
    return {
      success: true,
      data: data
    };
  } catch (error) {
    return {
      success: false,
      error: 'Invalid JSON format'
    };
  }
}

// 使用例1(ローカルストレージへの保存と読み込み)
const userData = {
  id: 1,
  name: "佐藤花子",
  email: "sato@example.com"
};
saveUserData(userData);
const loadedData = loadUserData();
console.log(loadedData); // { id: 1, name: "佐藤花子", email: "sato@example.com" }

// 使用例2(APIレスポンスの処理)
const apiResponse = '{"status":"success","data":{"id":1,"name":"山田次郎"}}';
const processedResponse = processApiResponse(apiResponse);
console.log(processedResponse); // { success: true, data: { status: 'success', data: { id: 1, name: '山田次郎' } } }

Date(日付)オブジェクト

ここでは、日付と時刻を扱うためのDateオブジェクトについて紹介します。

基本的な日付操作

// 現在の日時を取得
const now = new Date();
console.log(now); // 現在の日時

// 特定の日時を作成(月は0から始まることに注意)
const specificDate = new Date(2025, 0, 15, 10, 30, 0); // 2025年1月15日 10:30:00
console.log(specificDate);

// 文字列から日付を作成
const dateFromString = new Date("2025-01-15T10:30:00");
console.log(dateFromString);

// Unix timestamp から日付を作成
const dateFromTimestamp = new Date(1705320600000);
console.log(dateFromTimestamp);

日付の取得と設定

const date = new Date();

// 各要素の取得
console.log(date.getFullYear()); // 年
console.log(date.getMonth()); // 月(0から始まる)
console.log(date.getDate()); // 日
console.log(date.getHours()); // 時
console.log(date.getMinutes()); // 分
console.log(date.getSeconds()); // 秒

// 各要素の設定
date.setFullYear(2025);
date.setMonth(0); // 1月
date.setDate(15);
console.log(date);

日付のフォーマット

const date = new Date();

// 基本的なフォーマット
console.log(date.toDateString()); // "Mon Jan 15 2025"
console.log(date.toTimeString()); // "10:30:45 GMT+0900 (JST)"
console.log(date.toISOString()); // "2025-01-15T01:30:45.123Z"

// ローカライズされたフォーマット
console.log(date.toLocaleString("ja-JP")); // "2025/1/15 10:30:45"
console.log(date.toLocaleDateString("ja-JP")); // "2025/1/15"
console.log(date.toLocaleTimeString("ja-JP")); // "10:30:45"

// カスタムフォーマット(手動)
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

console.log(formatDate(new Date())); // "2025-01-15"

Intl(国際化)オブジェクト

Intlオブジェクトは、数値、日付、文字列の国際化対応フォーマットを提供します。

数値と通貨のフォーマット

const number = 1234567.89;

// 数値のフォーマット
const numberFormatter = new Intl.NumberFormat("ja-JP");
console.log(numberFormatter.format(number)); // "1,234,567.89"

// 通貨のフォーマット
const currencyFormatter = new Intl.NumberFormat("ja-JP", {
  style: "currency",
  currency: "JPY"
});
console.log(currencyFormatter.format(number)); // "¥1,234,568"

// パーセンテージのフォーマット
const percentFormatter = new Intl.NumberFormat("ja-JP", {
  style: "percent"
});
console.log(percentFormatter.format(0.75)); // "75%"

// 異なる地域での通貨フォーマット
const usdFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
});
console.log(usdFormatter.format(number)); // "$1,234,567.89"

日付のフォーマット

const date = new Date();

// 基本的な日付フォーマット
const dateFormatter = new Intl.DateTimeFormat("ja-JP");
console.log(dateFormatter.format(date)); // "2025/1/15"

// 詳細な日付フォーマット
const detailedFormatter = new Intl.DateTimeFormat("ja-JP", {
  year: "numeric",
  month: "long",
  day: "numeric",
  weekday: "long"
});
console.log(detailedFormatter.format(date)); // "2025年1月15日水曜日"

// 時刻を含むフォーマット
const datetimeFormatter = new Intl.DateTimeFormat("ja-JP", {
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit"
});
console.log(datetimeFormatter.format(date)); // "2025/01/15 10:30:45"

実践的なコード例

1. データの検証と処理

// ユーザー入力データの検証と処理
function validateAndProcessUser(userData) {
  const errors = [];
  const processed = {};

  // 名前の検証
  if (!userData.name || typeof userData.name !== 'string') {
    errors.push('名前は必須です');
  } else {
    processed.name = userData.name.trim();
  }

  // メールアドレスの検証
  if (!userData.email || !userData.email.includes('@')) {
    errors.push('有効なメールアドレスを入力してください');
  } else {
    processed.email = userData.email.toLowerCase().trim();
  }

  // 年齢の検証
  const age = Number(userData.age);
  if (isNaN(age) || age < 0 || age > 150) {
    errors.push('有効な年齢を入力してください');
  } else {
    processed.age = Math.floor(age);
  }

  return {
    isValid: errors.length === 0,
    errors: errors,
    data: processed
  };
}

// 使用例
const result = validateAndProcessUser({
  name: "  田中太郎  ",
  email: "TANAKA@EXAMPLE.COM",
  age: "30.5"
});

console.log(result);
// {
//   isValid: true,
//   errors: [],
//   data: { name: "田中太郎", email: "tanaka@example.com", age: 30 }
// }

2. タイマー機能の実装

// カウントダウンタイマークラス
class CountdownTimer {
  constructor(targetDate) {
    this.targetDate = new Date(targetDate);
    this.intervalId = null;
  }

  start(callback) {
    this.intervalId = setInterval(() => {
      const now = new Date();
      const difference = this.targetDate - now;

      if (difference <= 0) {
        this.stop();
        callback({ expired: true });
        return;
      }

      const days = Math.floor(difference / (1000 * 60 * 60 * 24));
      const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((difference % (1000 * 60)) / 1000);

      callback({
        expired: false,
        days,
        hours,
        minutes,
        seconds,
        formatted: `${days}${hours}時間 ${minutes}${seconds}秒`
      });
    }, 1000);
  }

  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
  }
}

// 使用例
const timer = new CountdownTimer("2025-12-31T23:59:59");
timer.start((timeLeft) => {
  if (timeLeft.expired) {
    console.log("時間切れです!");
  } else {
    console.log(`残り時間: ${timeLeft.formatted}`);
  }
});

3. レポート生成システム

// 売上データの分析とレポート生成
class SalesReporter {
  constructor(salesData) {
    this.salesData = salesData;
  }

  generateReport() {
    const totalSales = this.calculateTotalSales();
    const topProducts = this.getTopProducts(5);
    const salesByMonth = this.getSalesByMonth();

    return {
      period: this.getReportPeriod(),
      totalSales: this.formatCurrency(totalSales),
      totalOrders: this.salesData.length,
      averageOrderValue: this.formatCurrency(totalSales / this.salesData.length),
      topProducts: topProducts,
      monthlySales: salesByMonth,
      generatedAt: new Intl.DateTimeFormat("ja-JP", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      }).format(new Date())
    };
  }

  calculateTotalSales() {
    return this.salesData.reduce((total, sale) => total + sale.amount, 0);
  }

  getTopProducts(limit) {
    const productSales = {};

    this.salesData.forEach(sale => {
      if (productSales[sale.product]) {
        productSales[sale.product] += sale.amount;
      } else {
        productSales[sale.product] = sale.amount;
      }
    });

    return Object.entries(productSales)
      .sort(([,a], [,b]) => b - a)
      .slice(0, limit)
      .map(([product, amount]) => ({
        product,
        amount: this.formatCurrency(amount)
      }));
  }

  getSalesByMonth() {
    const monthlySales = {};

    this.salesData.forEach(sale => {
      const date = new Date(sale.date);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;

      if (monthlySales[monthKey]) {
        monthlySales[monthKey] += sale.amount;
      } else {
        monthlySales[monthKey] = sale.amount;
      }
    });

    return Object.entries(monthlySales)
      .map(([month, amount]) => ({
        month,
        amount: this.formatCurrency(amount)
      }))
      .sort((a, b) => a.month.localeCompare(b.month));
  }

  getReportPeriod() {
    const dates = this.salesData.map(sale => new Date(sale.date));
    const minDate = new Date(Math.min(...dates));
    const maxDate = new Date(Math.max(...dates));

    const formatter = new Intl.DateTimeFormat("ja-JP", {
      year: "numeric",
      month: "long",
      day: "numeric"
    });

    return `${formatter.format(minDate)}${formatter.format(maxDate)}`;
  }

  formatCurrency(amount) {
    return new Intl.NumberFormat("ja-JP", {
      style: "currency",
      currency: "JPY"
    }).format(amount);
  }
}

// 使用例
const salesData = [
  { date: "2025-01-01", product: "ノートPC", amount: 85000 },
  { date: "2025-01-02", product: "マウス", amount: 3000 },
  { date: "2025-01-03", product: "ノートPC", amount: 85000 },
  { date: "2025-01-15", product: "キーボード", amount: 8000 }
];

const reporter = new SalesReporter(salesData);
const report = reporter.generateReport();
console.log(JSON.stringify(report, null, 2));

復習

基本問題

1. 以下のコードの出力結果を予想する

const text = "JavaScript Programming";
console.log(text.includes("Script"));
console.log(text.startsWith("Java"));
console.log(text.repeat(2).length);

2. 配列の検索メソッドを使って、以下の条件を満たすコードを書く

const numbers = [1, 3, 5, 7, 9, 12, 15];

// すべて奇数かどうかを判定
// 10より大きい数が含まれているかを判定
// 最初に見つかる偶数を取得

3. Math オブジェクトを使って、1から100の間のランダムな整数を生成する関数を作成する

実践問題

4. JSON データを使った学生管理システムを作成する

以下の JSON データを使用して、学生の情報を管理するシステムを作成してください。

const studentsJson = `[
  {"id": 1, "name": "田中太郎", "scores": [85, 92, 78], "grade": "A"},
  {"id": 2, "name": "佐藤花子", "scores": [76, 84, 89], "grade": "B"},
  {"id": 3, "name": "山田次郎", "scores": [95, 88, 92], "grade": "A"}
]`;
要件
  • JSON データをパースして配列に変換
  • 全学生の平均点を計算
  • 成績が "A" の学生のみを抽出
  • 結果を見やすい形式で表示

5. 日付(Dateオブジェクト)とIntlオブジェクトを使って、多言語対応の予約システムを作成する

要件
  • 現在の日時を取得
  • 予約日時を指定の形式でフォーマット(日本語、英語)
  • 予約料金を各国の通貨形式で表示(日本円、米ドル)

解答例

問題1

const text = "JavaScript Programming";
console.log(text.includes("Script")); // true
console.log(text.startsWith("Java")); // true
console.log(text.repeat(2).length); // 44 ("JavaScript Programming"が22文字 × 2)

問題2

const numbers = [1, 3, 5, 7, 9, 12, 15];

// すべて奇数かどうかを判定
const allOdd = numbers.every(num => num % 2 !== 0);
console.log(allOdd); // false(12が偶数)

// 10より大きい数が含まれているかを判定
const hasLargeNumber = numbers.some(num => num > 10);
console.log(hasLargeNumber); // true

// 最初に見つかる偶数を取得
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 12

問題3

function getRandomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 使用例
console.log(getRandomInteger(1, 100)); // 1〜100のランダムな整数

問題4

function manageStudents(studentsJson) {
  // JSON をパース
  const students = JSON.parse(studentsJson);

  // 全学生の平均点を計算
  let totalScore = 0;
  let scoreCount = 0;

  students.forEach(student => {
    student.scores.forEach(score => {
      totalScore += score;
      scoreCount++;
    });
  });

  const overallAverage = totalScore / scoreCount;

  // 成績が "A" の学生のみを抽出
  const gradeAStudents = students.filter(student => student.grade === "A");

  // 結果を表示
  console.log("=== 学生管理システム ===");
  console.log(`全学生の平均点: ${Math.round(overallAverage)}点`);
  console.log("\n成績 A の学生:");

  gradeAStudents.forEach(student => {
    const studentAverage = student.scores.reduce((sum, score) => sum + score, 0) / student.scores.length;
    console.log(`${student.name}: 平均${Math.round(studentAverage)}点`);
  });

  return {
    overallAverage: Math.round(overallAverage),
    gradeAStudents: gradeAStudents
  };
}

// 実行
const result = manageStudents(studentsJson);

問題5

class ReservationSystem {
  constructor() {
    this.reservations = [];
  }

  createReservation(customerName, reservationDate, price) {
    const reservation = {
      id: Date.now(),
      customerName,
      reservationDate: new Date(reservationDate),
      price,
      createdAt: new Date()
    };

    this.reservations.push(reservation);
    return reservation;
  }

  formatReservation(reservation, locale = "ja-JP", currency = "JPY") {
    const dateFormatter = new Intl.DateTimeFormat(locale, {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit"
    });

    const currencyFormatter = new Intl.NumberFormat(locale, {
      style: "currency",
      currency: currency
    });

    return {
      customer: reservation.customerName,
      date: dateFormatter.format(reservation.reservationDate),
      price: currencyFormatter.format(reservation.price),
      createdAt: dateFormatter.format(reservation.createdAt)
    };
  }

  displayReservations() {
    console.log("=== 予約システム ===");

    this.reservations.forEach(reservation => {
      console.log("\n【日本語表示】");
      const jaFormat = this.formatReservation(reservation, "ja-JP", "JPY");
      console.log(`お客様: ${jaFormat.customer}`);
      console.log(`予約日時: ${jaFormat.date}`);
      console.log(`料金: ${jaFormat.price}`);

      console.log("\n【English Display】");
      const enFormat = this.formatReservation(reservation, "en-US", "USD");
      console.log(`Customer: ${enFormat.customer}`);
      console.log(`Reservation: ${enFormat.date}`);
      console.log(`Price: ${enFormat.price}`);
      console.log("---");
    });
  }
}

// 使用例
const system = new ReservationSystem();
system.createReservation("田中太郎", "2025-02-14T19:00:00", 5000);
system.createReservation("Smith John", "2025-02-15T20:30:00", 7500);
system.displayReservations();

まとめ

JavaScriptの組み込みオブジェクトとユーティリティ機能について、実践的な活用方法を中心に紹介しました。

技術的メリット

  1. 効率的な文字列操作
    • includes(), repeat(), padStart()などのメソッドで可読性の高いコードを書ける
    • replaceAll()により全置換が簡潔に記述できる
  2. 配列操作の向上
    • find(), some(), every()により条件に基づく直感的な検索・判定
    • 従来のfor文よりも意図が明確なコードになる
  3. 数学計算の簡素化
    • Mathオブジェクトにより複雑な計算が組み込み関数で用意されている
      • ランダム値生成や数値フォーマット
  4. データ交換の標準化
    • JSON.parse()/JSON.stringify()でAPI通信やストレージ操作が簡単
    • エラーハンドリングと組み合わせて堅牢な処理が可能

活用場面

  • ユーザー入力の検証
    文字列メソッドと数値チェックを組み合わせたバリデーション
  • データ分析
    配列メソッドによる集計
  • 時間管理
    Dateオブジェクトを使ったタイマーやスケジュール機能
  • 国際化対応
    Intlオブジェクトによる多地域・多通貨対応

注意すべきポイント

Dateオブジェクトには直感的でない動作(月が0から始まる、など)があるため、使用時は十分な注意が必要です。なお、Temporal API(12回目の記事で取り上げます)など、より使いやすい日付操作を可能にする方法やライブラリもあります。

JSON操作時は必ずtry-catch文でエラーハンドリングを行ない、不正なデータ形式に対する対策を講じることが重要です。


次回 は、DOM操作とイベント処理について、モダンなWebアプリケーション開発に必要な技術を中心に紹介します。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?