すべてのチートシートを表示
Seiwa Holdings Seiwa Holdings

JavaScriptチートシート

クイックリファレンス用の必須JavaScriptコンセプトと構文

javascript ウェブ開発 プログラミング

JavaScriptチートシート

基本概念

変数宣言

// 変数宣言
let variable = '値'; // ブロックスコープ、再代入可能
const constant = '値'; // ブロックスコープ、再代入不可
var oldVariable = '値'; // 関数スコープ、使用は避けるべき

プリミティブデータ型

let string = 'Hello world'; // 文字列
let number = 42; // 数値
let boolean = true; // ブール値
let nullValue = null; // Null
let undefinedValue; // Undefined
let symbol = Symbol('説明'); // シンボル
let bigInt = 1234567890123456789012345678901234567890n; // BigInt

参照データ型

let array = [1, 2, 3]; // 配列
let object = { key: 'value' }; // オブジェクト
let date = new Date(); // Dateオブジェクト
let regex = /\d+/g; // 正規表現
let map = new Map(); // Map
let set = new Set(); // Set

関数

関数宣言

// 関数宣言
function functionName(param1, param2) {
  return param1 + param2;
}

// 関数式
const functionExpression = function(param1, param2) {
  return param1 + param2;
};

アロー関数

// ブロック本体を持つアロー関数
const arrowFunction = (param1, param2) => {
  return param1 + param2;
};

// 暗黙的な返値を持つアロー関数
const shortArrowFunction = (param1, param2) => param1 + param2;

// 単一パラメータのアロー関数(括弧はオプション)
const singleParam = param => param * 2;

関数パラメータ

// デフォルトパラメータ
function defaultParams(param1 = 'デフォルト値') {
  return param1;
}

// レストパラメータ
function restParams(param1, ...restOfParams) {
  console.log(param1); // 'a'
  console.log(restOfParams); // ['b', 'c', 'd']
}
restParams('a', 'b', 'c', 'd');

// パラメータの分割代入
function destructureParams({ name, age }) {
  console.log(`${name}は${age}歳です`);
}
destructureParams({ name: '太郎', age: 30 });

配列

配列の作成とアクセス

// 配列の作成
let array1 = [1, 2, 3, 4, 5];
let array2 = new Array(1, 2, 3);
let filledArray = Array(5).fill(0); // [0, 0, 0, 0, 0]

// 要素へのアクセス
array1[0]; // 最初の要素
array1[array1.length - 1]; // 最後の要素

配列の操作メソッド

// 要素の追加と削除
array.push(6); // 末尾に追加: [1, 2, 3, 4, 5, 6]
array.pop(); // 末尾から削除: [1, 2, 3, 4, 5]
array.unshift(0); // 先頭に追加: [0, 1, 2, 3, 4, 5]
array.shift(); // 先頭から削除: [1, 2, 3, 4, 5]

// スライスとスプライス
array.slice(1, 3); // [2, 3]を返す(元の配列は変更されない)
array.splice(1, 2, 'a', 'b'); // [2, 3]を返し、arrayは[1, 'a', 'b', 4, 5]になる

配列の反復処理メソッド

// 基本的な反復処理
array.forEach(item => console.log(item));

// 配列の変換
array.map(item => item * 2); // 各要素を2倍にした新しい配列を返す

// 配列のフィルタリング
array.filter(item => typeof item === 'number'); // 数値のみを返す

// 要素の検索
array.find(item => item > 3); // 3より大きい最初の要素を返す
array.findIndex(item => item > 3); // 3より大きい最初の要素のインデックスを返す

// 配列のテスト
array.some(item => item > 3); // 3より大きい要素が1つでもあればtrueを返す
array.every(item => item > 0); // すべての要素が0より大きければtrueを返す

// 配列の縮小
array.reduce((acc, item) => acc + item, 0); // すべての要素の合計

高度な配列メソッド

// 配列のフラット化
const nestedArray = [1, [2, 3], [4, [5, 6]]];
nestedArray.flat(); // [1, 2, 3, 4, [5, 6]]
nestedArray.flat(2); // [1, 2, 3, 4, 5, 6]

// マップとフラット化を1回の操作で行う
const numbers = [1, 2, 3];
numbers.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]

// 配列風オブジェクトから配列を作成
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]

// インデックスに基づいて値を持つ配列を作成
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]

オブジェクト

オブジェクトの作成とアクセス

// オブジェクトリテラル
let person = {
  name: '太郎',
  age: 30,
  greet() {
    return `こんにちは、私の名前は${this.name}です`;
  }
};

// プロパティへのアクセス
person.name; // '太郎'
person['age']; // 30
person.greet(); // 'こんにちは、私の名前は太郎です'

オブジェクトメソッド

// オブジェクトプロパティ操作
Object.keys(person); // ['name', 'age', 'greet']
Object.values(person); // ['太郎', 30, [Function: greet]]
Object.entries(person); // [['name', '太郎'], ['age', 30], ['greet', [Function: greet]]]

// エントリーからオブジェクトを作成
Object.fromEntries([['name', '花子'], ['age', 25]]); // { name: '花子', age: 25 }

// オブジェクトプロパティディスクリプタ
Object.getOwnPropertyDescriptor(person, 'name');
Object.defineProperty(person, 'id', { value: 42, writable: false });

オブジェクト操作

// スプレッド演算子
let newPerson = { ...person, job: '開発者' };

// オブジェクトの分割代入
let { name, age } = person;
let { name: personName, age: personAge } = person; // 変数名の変更

// オブジェクトのマージ
Object.assign({}, obj1, obj2);

// プロパティの確認
'name' in person; // true
person.hasOwnProperty('name'); // true

高度なJavaScript

クラスとプロトタイプ

// ES6 クラス
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    return `こんにちは、私の名前は${this.name}です`;
  }
  
  static createAnonymous() {
    return new Person('匿名', 0);
  }
}

// 継承
class Employee extends Person {
  constructor(name, age, company) {
    super(name, age);
    this.company = company;
  }
  
  greet() {
    return `${super.greet()}、${this.company}で働いています`;
  }
}

プロトタイプ継承(ES6以前)

// コンストラクタ関数
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// プロトタイプにメソッドを追加
Person.prototype.greet = function() {
  return `こんにちは、私の名前は${this.name}です`;
};

// インスタンスの作成
const john = new Person('太郎', 30);

プロミスとAsync/Await

// プロミスの作成
const promise = new Promise((resolve, reject) => {
  // 非同期処理
  if (success) {
    resolve(result);
  } else {
    reject(error);
  }
});

// プロミスの使用
promise
  .then(result => console.log(result))
  .catch(error => console.error(error))
  .finally(() => console.log('処理完了'));

// Async/Await
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('データ取得エラー:', error);
  }
}

プロミスコンビネータ

// プロミスを並行実行し、すべての完了を待つ
Promise.all([promise1, promise2, promise3])
  .then(([result1, result2, result3]) => {
    // すべてのプロミスが成功した場合
  })
  .catch(error => {
    // 少なくとも1つのプロミスが失敗した場合
  });

// 最初に完了したプロミスを取得
Promise.race([promise1, promise2, promise3])
  .then(result => {
    // 最初に成功/失敗したプロミスの結果
  });

// すべてのプロミスの結果を待つ
Promise.allSettled([promise1, promise2, promise3])
  .then(results => {
    // { status: 'fulfilled'/'rejected', value/reason: ... } の配列
  });

// 最初に成功したプロミスを取得(失敗は無視)
Promise.any([promise1, promise2, promise3])
  .then(result => {
    // 最初に成功したプロミスの結果
  })
  .catch(errors => {
    // すべてのプロミスが失敗した場合
  });

モジュール

// エクスポート
export const PI = 3.14159;
export function square(x) {
  return x * x;
}
export default class Calculator { /* ... */ }

// インポート
import Calculator, { PI, square } from './math.js';
import * as math from './math.js';
import('./math.js').then(module => {
  // 動的インポート
});

ジェネレータとイテレータ

// ジェネレータ関数
function* numberGenerator() {
  yield 1;
  yield 2;
  yield 3;
}

// ジェネレータの使用
const generator = numberGenerator();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }

// ジェネレータの反復処理
for (const num of numberGenerator()) {
  console.log(num); // 1, 2, 3
}

Web API

Fetch API

// 基本的なfetchリクエスト
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTPエラー! ステータス: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Fetchエラー:', error));

// オプション付きのfetch
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  },
  body: JSON.stringify({ key: 'value' })
});

ローカルストレージとセッションストレージ

// ローカルストレージ(ブラウザを閉じても持続)
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');
localStorage.clear();

// セッションストレージ(ブラウザを閉じるとクリア)
sessionStorage.setItem('key', 'value');
const sessionValue = sessionStorage.getItem('key');

DOM操作

// 要素の選択
const element = document.getElementById('id');
const elements = document.querySelectorAll('.class');

// 要素の作成と変更
const newElement = document.createElement('div');
newElement.textContent = 'Hello World';
newElement.classList.add('my-class');
document.body.appendChild(newElement);

// イベント処理
element.addEventListener('click', (event) => {
  event.preventDefault();
  console.log('要素がクリックされました');
});

正規表現

// 正規表現の作成
const regex1 = /パターン/フラグ;
const regex2 = new RegExp('パターン', 'フラグ');

// 一般的なフラグ
// g - グローバルマッチ
// i - 大文字小文字を区別しない
// m - 複数行
// s - ドットが改行にマッチ
// u - Unicode
// y - スティッキー

// テストとマッチ
regex.test('文字列'); // ブール値を返す
'文字列'.match(regex); // マッチの配列を返す
'文字列'.replace(regex, '置換'); // 新しい文字列を返す

エラー処理

// try-catchブロック
try {
  // エラーを発生させる可能性のあるコード
  throw new Error('何かが間違っています');
} catch (error) {
  console.error('エラーを捕捉:', error.message);
} finally {
  // 常に実行される
  console.log('クリーンアップコード');
}

// カスタムエラークラス
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
  }
}

// カスタムエラーを投げる
throw new ValidationError('無効な入力');