配列からランダムアイテムを取得するJavaScriptプログラム

Javascript

例:配列からランダムアイテムを取得する

// program to get a random item from an array

function getRandomItem(arr) {

    // get random index value
    const randomIndex = Math.floor(Math.random() * arr.length);

    // get random item
    const item = arr[randomIndex];

    return item;
}

const array = [1, 'hello', 5, 8];

const result = getRandomItem(array);
console.log(result);

出力

'hello'

上記のプログラムでは、配列からランダムなアイテムにアクセスします。

  • 間の乱数 0array.length を使用して生成されます Math.random() 方法。
  • ザ・ Math.floor() によって生成された最も近い整数値を返します Math.random()
  • 次に、このランダムインデックスを使用して、ランダム配列要素にアクセスします。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です