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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744710793a4589330.html
评论列表(0条)