JavaScript 從陣列中選取隨機值

Ammar Ali 2023年10月12日

使用 JavaScript 中的 `Math.random()` 函式從陣列中選擇一個隨機值

`Math.random()` 函式生成的隨機值是一個浮點值。要將浮點值轉換為整數，我們必須使用 `Math.floor()` 函式。`Math.floor()` 函式將浮點數轉換為小於給定數字的整數。例如，讓我們建立一個包含五個值的陣列並從中隨機選擇一個值並將其顯示在控制檯上。請參考下面的程式碼。

``````var myArray = ['one', 'two', 'three', 'four', 'five'];
var rand = Math.floor(Math.random() * myArray.length);
var rValue = myArray[rand];
console.log(rValue)
``````

``````two
``````

``````var myArray = ['one', 'two', 'three', 'four', 'five'];
var rand = ~~(Math.random() * myArray.length);
var rValue = myArray[rand];
console.log(rValue)
``````

``````one
``````

``````var myArray = ['one', 'two', 'three', 'four', 'five'];
var rand = Math.random() * myArray.length | 0;
var rValue = myArray[rand];
console.log(rValue)
``````

``````three
``````

``````function RandArray(array) {
var rand = Math.random() * array.length | 0;
var rValue = array[rand];
return rValue;
}
var myArray = ['one', 'two', 'three', 'four', 'five', 'six'];
var rValue = RandArray(myArray);
console.log(rValue)
``````

``````six
``````

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook