// 定义一个数组
const array = ['apple', 'banana', 'cherry', 'date'];
// 获取数组的随机索引
const randomIndex = Math.floor(Math.random() * array.length);
// 通过随机索引取出数组中的元素
const randomElement = array[randomIndex];
console.log(randomElement); // 输出随机取出的数组元素
// 解释说明:
// 1. Math.random() 返回一个 0 到 1 之间的随机小数(不包括 1)。
// 2. Math.random() * array.length 生成一个 0 到数组长度之间的随机小数。
// 3. Math.floor() 将上述结果向下取整,得到一个有效的数组索引。
// 4. array[randomIndex] 通过随机索引取出数组中的一个元素。
上一篇:js 遍历json数组
下一篇:js json 数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站