This article mainly introduces how to add a random element to the JavaScript array object, involving javascript related operations on arrays and random numbers, for more information about how to add a random element to a JavaScript Array object, see the example in this article. Share it with you for your reference. The details are as follows:
Core features:
Random probability, random order, and random bubble
This method is applicable only to the JavaScript 1.5 (ECMAscript 3 International Standard) language ~
Add the random method to 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); };})();
Example:
// [Probability random] // the return of an element is completely random, and the probability of occurrence is not fixed. A limited call cannot guarantee that all elements are returned. var iElement = iArray. random (); // [random order] // elements are returned cyclically. The elements appear once in each cycle, but the order is not fixed. var iElement = iArray. random (true); // [random bubble] /// each call will randomly retrieve an element from the original array and return the result (the original array is changed in place) var iElement = iArray. random (true, true );
I hope this article will help you design javascript programs.