Javascript中的.sample等于什么?

bea*_*akr 2 javascript ruby methods google-chrome-extension

我正在开发一个即将发布的小型Chrome扩展程序,但是在此扩展程序中,我必须从数组中随机抽取一项并将其显示在屏幕上。过去,我使用了大量的Ruby代码,还记得方法'.sample',该方法在屏幕上显示来自数组的随机项目。

示例(在Ruby中):

farm_animals = ['cow', 'chicken', 'pig', 'horse']
puts farm_animals.sample
Run Code Online (Sandbox Code Playgroud)

输出结果可能像...

>> cow
Run Code Online (Sandbox Code Playgroud)

在Javascript中是否有与此便捷数组方法等效的方法?谢谢!

nod*_*rog 5

尝试:

var farm_animals = ['cow', 'chicken', 'pig', 'horse']
alert(farm_animals[Math.floor ( Math.random() * farm_animals.length )])
Run Code Online (Sandbox Code Playgroud)

或作为功能:

function sample(array) {
  return array[Math.floor ( Math.random() * array.length )]
}

console.log(sample(farm_animals))
Run Code Online (Sandbox Code Playgroud)