# 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.