var items = Array(523,3452,334,31,...5346);
How do I get random item from items
?
I am using jQuery, so answers involving jQuery are welcome.
How do I get random item from I am using jQuery, so answers involving jQuery are welcome. |
|||||||||||||||||||||
|
|
|||||||||||||||||||||
|
If you really must use jQuery to solve this problem:
This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value! For extra fun, the array return is generated by calling the function recursively based on the array's length :) Working demo at http://jsfiddle.net/2eyQX/ |
|||||||||||||
|
Use underscore (or loDash :)):
Or to shuffle an entire array:
|
|||||||||||||||||
|
|
|||
|
|
|||
|
jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,
|
||||
|
credit: http://www.earn-web-cash.com/2008/02/24/random-number-function/ |
|||||
|
Shorter:
|
|||||||||||||
|
Here's yet another way:
|
|||||||||
|
If you are using node.js, you can use unique-random-array. It simply picks something random from an array. |
|||
|
1. solution: define Array prototype
that will work on inline arrays
and of course predefined arrays
2. solution: define custom function that accepts list and returns element
|
|||
|
An alternate way would be to add a method to the Array prototype:
|
|||||||||||||||||
|
|
||||
|