【问题标题】:What's the equivalent of .sample in Javascript?Javascript 中的 .sample 等价物是什么?
【发布时间】:2012-02-15 00:54:09
【问题描述】:

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

示例(在 Ruby 中):

farm_animals = ['cow', 'chicken', 'pig', 'horse']
puts farm_animals.sample

输出可能最终会像...

>> cow

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

【问题讨论】:

  • 我不熟悉 Ruby,在 google 中寻找 .sample 并没有找到任何东西。你能指出我可以看到样本的作用的方向吗?我可能会帮助你
  • @Seth 这是 Rubydocs Array 类和方法。 .sample 方法按字母顺序在侧面板上,我有指向 .sample 区域的快速链接。 ruby-doc.org/core-1.9.3/Array.html#method-i-sample

标签: javascript ruby methods google-chrome-extension


【解决方案1】:

试试:

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[...] 之前忘记了return,它从那里开始工作,谢谢!
  • 嘿,这需要习惯。您也可以添加一些分号。 :-P
  • 真的需要吗?又是红宝石!我已经写了很多 javascript 并且很少需要它们
  • 在你的情况下,函数的内容可以没有一个,因为在最后一行(在你的情况下是第一行)函数中你可以没有一个并且它会工作。但是console.log 应该有一个。有时我开始认为 Ruby 为你做的太多了。 :-P
【解决方案2】:

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

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

然后

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

给你一个随机元素。

很多——很多,大多数——人们会说这样一个不太有用的函数不值得像这样污染内置原型的罪过。追随你的幸福。

【讨论】:

  • @Vigrond 是的,但是修改内置类的原型对象会产生互操作性后果。
  • 你能解释一下双位吗?没关系,我现在看到您正在使用它作为 Math.floor 的简写
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2014-12-06
  • 2011-04-23
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多