LoginSignup
4
1

More than 3 years have passed since last update.

【TypeScript】ランダムにカラーコードを生成する

Last updated at Posted at 2020-01-17

#000000#ffffffのカラーコードをランダムに生成する関数。

export const randomColor = () => {
  return "#" + [0, 1, 2, 3, 4, 5]
    .map(_ => Math.floor(Math.random() * 0x10).toString(16))
    .join("");
}

Math.floor(Math.random() * 0x10)で0~15の乱数を生成してtoString(16)で16進数文字列に変換。
その処理を要素6つの配列の中で行い6つの16進数文字列を取得する。
最後にjoin("")で結合して"#"とも結合して返却する。

for文を使わず読みやすいかと思います。

4
1
4

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
4
1