English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example of Randomly Shuffling Array Method in JS

This article describes the method of generating a random shuffle array in JavaScript. Shared for everyone's reference, as follows:

One, a chaotic sorting method

function fnLuanXu(num) {
    var aLuanXu=[];
    for (var i = 0; i < num; i++) {
      aLuanXu[i] = i;
    }
    for (var i = 0; i < num; i++) {
      var iRand = parseInt(num * Math.random());
      var temp = aLuanXu[i];
      aLuanXu[i] = aLuanXu[iRand];
      aLuanXu[iRand] = temp;
      //console.log('i='+i+';temp='+temp+';rand='+iRand+';array['+i+']='+aLuanXu[i]+';array['+iRand+']='+aLuanXu[iRand]+';array=['+aLuanXu+'];');
    }
    return aLuanXu;
}
//Test:
console.log(fnLuanXu(6));

Running result:

Secondly, a less chaotic sorting method, a built-in JavaScript function.

function fnLuanXu(num) {
    var aLuanXu=[];
    for (var i = 0; i < num; i++) {
      aLuanXu[i] = i;
    }
    aLuanXu.sort(function(){return Math.random()>0.5?-1:1;}
    return aLuanXu;
}
//Test:
console.log(fnLuanXu(7));

Running result:

PS: Here are several related online tools for your reference and use:

Online random number/String generation tool:
http://tools.jb51.net/aideddesign/suijishu

Online Chinese and English alphabetical sorting tool:
http://tools.jb51.net/aideddesign/zh_paixu

Online text reverse sorting tool:
http://tools.jb51.net/aideddesign/flipped_txt

Readers who are interested in more about JavaScript-related content can check out the special topics on this site: 'Summary of JavaScript Mathematical Operation Usage', 'Summary of JavaScript Data Structure and Algorithm Techniques', 'Summary of JavaScript Array Operation Techniques', 'Summary of JavaScript Sorting Algorithm', 'Summary of JavaScript Traversal Algorithm and Techniques', 'Summary of JavaScript Search Algorithm Techniques', and 'Summary of JavaScript Error and Debugging Techniques'.

I hope this article will be helpful to everyone in programming JavaScript.

Declaration: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please report violations by email to codebox.com (replace # with @) and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.

You May Also Like