什么'相当于Javascript中的.sample

What's the equivalent of .sample in Javascript?

本文关键字:Javascript 中的 sample 相当于 什么      更新时间:2023-09-26

我正在开发一个即将发布的小型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))

如果你不反对破解内置对象原型:

Array.prototype.sample = function() {
  return this[~~(Math.random() * this.length)];
}

然后

var samp = ["hello", "friendly", "world"].sample();

给你一个随机元素。

很多—很多,大多数;人们会说,这样一个不那么有用的功能不值得污染这样一个内置原型。追随你的幸福。