sample - 数组取样,随机获取数组中的一个元素

优质
小牛编辑
124浏览
2023-12-01

从数组中随机返回一个元素。

使用 Math.random() 生成一个随机数,乘以 length,并使用 Math.floor() 舍去小数获得到最接近的整数。这个方法也适用于字符串。

const sample = arr => arr[Math.floor(Math.random() * arr.length)];
sample([3, 7, 9, 11]); // 9