JavaScript Array Object Implementation adds a method to return random elements

Source: Internet
Author: User

Add the random method for the array object:

(function () {
function Random_sn (IArray) {
Return Math.floor (Math.random () * iarray.length);
}
function Probability_random (IArray) {
var random_int;
if (iarray.random_sn = = undefined)
IARRAY.RANDOM_SN =-1;
Do random_int = RANDOM_SN (IArray);
while (Random_int = = IARRAY.RANDOM_SN)
IARRAY.RANDOM_SN = Random_int;
return Iarray[random_int];
}
function Sequence_random (IArray) {
Return Iarray.splice (RANDOM_SN (IArray), 1) [0];
}
Array.prototype.random = function (Mode, Pop) {
if (! Mode)
Return Probability_random (this);
if (! POP) {
if (! (This. Random_queue && this. Random_queue.length))
This. Random_queue = [].concat (this);
Return Sequence_random (this. Random_queue);
}
Return Sequence_random (this);
};
})();

Use examples:

"Random Probability"
//
The return of elements is completely random, the probability of occurrence is uncertain, and a finite number of calls is not guaranteed to return all elements
var ielement = Iarray.random ();
"Sequential random"
//
The return of the element is periodic, and the elements appear once in each cycle, but in a sequential order
var ielement = Iarray.random (true);
"Random Bubbling"
//
Each call takes a random fetch of an element from the original array and returns (the original array changes in place)
var ielement = Iarray.random (True, true);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.