JavaScript で配列からランダムな要素を取得する


プレゼント アプリケーションを作成したとします.今日はラッフルです.残念ながら、10 人の参加者のリストがありますが、そのうちの 1 人を勝者としてランダムに選択する方法がわかりません.

心配しないで!数分で、JavaScript で配列からランダムな要素を取得できるようになります!

数学関数を使用して配列からランダム要素を選択する方法



これは、配列からランダムな要素を取得するための 1 行の命令です: YOUR_ARRAY[Math.floor(Math.random() * YOUR_ARRAY.length)] .

この命令を中断して、それが何をするのかを理解しましょう.
  • YOUR_ARRAY は配列変数です (この場合、10 人の参加者の電子メール アドレス)
  • YOUR_ARRAY.length は、配列
  • のサイズを返す配列プロパティです.
  • Math.random() は、0 から 1 未満 (0 を含むが 1 は含まない) の範囲の疑似乱数を返す関数です.
  • Math.floor() は、指定された数値
  • 以下の最大の整数を返す関数です.

    Note: As Mozilla mentions, Math.random() does not provide cryptographically secure random numbers. It's not recommended to use them for anything related to security. Use the Web Crypto API instead, and more precisely, the window.crypto.getRandomValues() method.



    各手順を理解できたので、順を追って例を示します.

    const participants = [
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
    ]
    
    console.log(participants.length)
    // Output: 10
    
    console.log(Math.random())
    // Output: random number between 0 or 1 (ex: 0.623242121481016)
    
    console.log(Math.random() * participants.length)
    // Output: random number between 0 or 1 multiplied by 10 (ex: 0.623242121481016 * 10 = 1.6905986987355703)
    
    console.log(Math.floor(Math.random() * participants.length))
    // Output: it takes the larger integer less than or equal to a given number (ex: Math.floor(1.6905986987355703) = 1)
    


    Note: If you try the code above, the result will always be different because of the Math.random() function.



    ここにいます!いよいよプレゼント当選者決定!そのために、この記事で学んだことをユースケースで使用します.

    const participants = [
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
    ] // 10 participants
    
    const winner = participants[Math.floor(Math.random() * participants.length)]
    
    console.log(winner)
    // Output is random (launch this code to see who is the winner :D)
    


    そう!ジャックポットを獲得したのは誰ですか? 😉


    ➡️ Web 開発者のスキル向上をお手伝いします 💻 Web プログラミングに関するヒントやリソースをもっと知りたい場合 ->