碎片時間學(xué)編程「340]:從數(shù)組中獲取一個隨機(jī)元素

從數(shù)組中獲取一個隨機(jī)元素。 使用 Math.random() 方法生成隨機(jī)數(shù)。 將其乘以 Array.prototype.length 方法并使用 Math.floor() 方法將其四舍五入為最接近的整數(shù)。 此方法也適用于字符串。
JavaScript
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
示例:
sample([3, 7, 9, 11]); // 9
更多內(nèi)容請?jiān)L問我的網(wǎng)站:https://www.icoderoad.com
標(biāo)簽: