sho-darpのWebsite

JavaScript (TypeScript)のスニペット集

JavaScript TypeScript

よく使いそう

待機処理

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
  console.log("Hello, ");
  await wait(1000);

  // 1000ミリ秒後に表示される
  console.log("World");
}

main();

配列の重複排除

const duplicate_fruits = ["apple", "banana", "apple", "orange", "banana"];

const fruits = [...new Set(duplicate_fruits)];
console.log(fruits);
// ["apple", "banana", "orange"]

配列の合計

const sum = (array: number[]) => array.reduce((a, b) => a + b, 0);

const price = [1000, 500, 3000];
console.log(sum(price));
// => 4500

Array.prototype.reduce()を使うことで、配列の要素を1つずつ処理することができます。 上の処理は以下のようになります。

// reduceの第1引数は2つの要素をどのように処理するか => 足し算
// reduceの第2引数は初期値 => 0


// 1回目
// 初期値 + 1つ目の要素
0 + 1000 = 1000

// 2回目
// 1回目の合計値 + 2つ目の要素
1000 + 500 = 1500

// 3回目(すべての要素を処理したので終了)
// 2回目の合計値 + 3つ目の要素
1500 + 3000 = 4500

OR条件

同じ変数に対して複数のOR条件がある場合は、簡潔に書くことができます。
ただし、速度面で不利になる可能性があるためパフォーマンスを重視する場合は注意が必要かもしれません。

const fruit = "apple";

// OR 演算子を使う場合
if (fruit === "apple" || fruit === "banana" || fruit === "orange") {
  console.log("It's favorite fruit.");
}

// Array.protptype.includes() を使う場合
if (["apple", "banana", "orange"].includes(fruit)) {
  console.log("It's favorite fruit.");
}