我正在开发一个即将发布的小型 Chrome 扩展程序,但是在这个扩展程序中,我必须从数组中随机取一个项目并将其显示在屏幕上。过去,我使用过很多 Ruby 代码,还记得方法“.sample”,它在屏幕上显示数组中的随机项。
示例(在 Ruby 中):
farm_animals = ['cow', 'chicken', 'pig', 'horse']
puts farm_animals.sample
输出最终可能是这样的……
>> cow
在 Javascript 中是否有与这个方便的数组方法等效的方法?谢谢!
最佳答案
尝试:
var farm_animals = ['cow', 'chicken', 'pig', 'horse']
alert(farm_animals[Math.floor ( Math.random() * farm_animals.length )])
或作为函数:
function sample(array) {
return array[Math.floor ( Math.random() * array.length )]
}
console.log(sample(farm_animals))
关于javascript - Javascript 中的 .sample 等同于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9286473/