Home  >  Article  >  Web Front-end  >  JavaScript array object implementation adds a method to return random elements_javascript skills

JavaScript array object implementation adds a method to return random elements_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:48:431334browse

The example in this article describes the implementation of a JavaScript array object to add a method that returns random elements. Share it with everyone for your reference. The details are as follows:

Core features:

Random probability, random order, random bubbling

This method comes from personal handwriting JavaScript practice, only involves the JavaScript 1.5 (ECMAscript 3 international standard) language itself, and is common in all JS engine implementations~

Add random method to 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);
  };
})();

Usage example:

// 【概率随机】
//
// 元素的返回 完全随机,出现几率不定,有限次调用不保证能返回所有元素
var iElement = iArray.random();
// 【顺序随机】
//
// 元素的返回 有周期性,在每个周期内,元素都出现一次,但顺序不定
var iElement = iArray.random(true);
// 【随机冒泡】
//
// 每次调用都从原数组中随机取出一个元素返回(原数组 就地改变)
var iElement = iArray.random(true, true);

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn