The example in this article describes a method for adding a random element to a JavaScript array object implementation. Share to everyone for your reference. Specifically as follows:
Core Features:
Probabilistic random, sequential random, random bubbling
This method comes from the practice of personal handwriting JavaScript, only involves JavaScript 1.5 (ECMAscript 3 international Standard) language itself, in all JS engine implementations
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 to
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:
"Probabilistic random"////
element return is completely random, the probability of occurrence is uncertain, and a finite number of calls does not guarantee that all elements of
var ielement = Iarray.random () can be returned;
The "sequential random"////
element return is periodic, and the elements appear once in each cycle, but the order is variable
var ielement = Iarray.random (true);
"Random bubbling"////
each call randomly extracts an element from the original array to return (the original array changes in place)
var ielement = Iarray.random (True, true);
I hope this article will help you with your JavaScript programming.