admin管理员组文章数量:1391991
I'm working on a small Chrome extension soon to be released, however in this extension I must take a random item from an array and display it on the screen. In the past, I've worked with a lot of Ruby code, and remember the method '.sample' which displays a random item from an array on the screen.
Example (in Ruby):
farm_animals = ['cow', 'chicken', 'pig', 'horse']
puts farm_animals.sample
The output could end up being something like...
>> cow
Is there an equivalent to this handy array method in Javascript? Thanks!
I'm working on a small Chrome extension soon to be released, however in this extension I must take a random item from an array and display it on the screen. In the past, I've worked with a lot of Ruby code, and remember the method '.sample' which displays a random item from an array on the screen.
Example (in Ruby):
farm_animals = ['cow', 'chicken', 'pig', 'horse']
puts farm_animals.sample
The output could end up being something like...
>> cow
Is there an equivalent to this handy array method in Javascript? Thanks!
Share Improve this question edited Oct 30, 2019 at 19:57 lacostenycoder 11.3k4 gold badges36 silver badges50 bronze badges asked Feb 15, 2012 at 0:54 beakrbeakr 5,86713 gold badges45 silver badges66 bronze badges 2-
1
I'm not familiar with Ruby and looking for
.sample
in google didn't turn up anything. Can you point me in a direction where I can see what sample does and I can likely help you out – Seth Commented Feb 15, 2012 at 0:58 - @Seth Here's the Rubydocs Array class & methods. THe .sample method is on the side panel in alphabetical order, and I've got the quick link to the .sample area. ruby-doc/core-1.9.3/Array.html#method-i-sample – beakr Commented Feb 15, 2012 at 1:04
2 Answers
Reset to default 5Try:
var farm_animals = ['cow', 'chicken', 'pig', 'horse']
alert(farm_animals[Math.floor ( Math.random() * farm_animals.length )])
or as a function:
function sample(array) {
return array[Math.floor ( Math.random() * array.length )]
}
console.log(sample(farm_animals))
If you're not averse to hacking built-in object prototypes:
Array.prototype.sample = function() {
return this[~~(Math.random() * this.length)];
}
Then
var samp = ["hello", "friendly", "world"].sample();
gives you a random element.
A lot — many, most — people would say that such a not-so-useful function would not be worth the sin of polluting a built-in prototype like that. Follow your bliss.
本文标签: rubyWhat39s the equivalent of sample in JavascriptStack Overflow
版权声明:本文标题:ruby - What's the equivalent of .sample in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744710792a2621116.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论