このような配列がある場合:
var arr1 = ["a"、 "b"、 "c"、 "d"];
アレイの順序をランダムに破壊する方法、つまりシャッフルします。
広く拡散している単純なランダムアルゴリズムがあります。
関数randomsort(a、b){return(0.5 -math.random()); }実際、上記が完全にランダムではないことが証明されています。
インターネット上であまりにも多くのそのようなことを検索しました。 Stackoverflowの高得点の答えを見てみましょう。答えはGithubから来ています。
クヌースシャッフル
Fisher-Yates(別名Knuth)ブラウザとnode.jsのシャッフル
上記のアルゴリズムを見てみましょう。コードは次のとおりです。
/ *jshint -w054 */(function(exports){'s strict'; // http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-arrayfunction shuffle(array){var currentIndex = arement = arements = runcilevalue ... !== currentIndex){//残り要素を選択... randomindex = math.floor(math.random() * currentindex); currentIndex- = 1; // shuffle;}( 'undefined'!== typeof exports && exports || '未定義'!== windof && window || global));著者は、ブラウザ作成方法を使用することをお勧めします。
(function(){'sprict'; var a = [2,11,37,42]、b; // shuffleは元の配列// a.slice(0)を呼び出します。nodejs:
npm install -s knuth-shuffle(function(){'sprict'; var shuffle = require( 'knuth-shuffle')。knuthshuffle、a = [2,11,37,42]、b; shuffle(a.slice(0)); console.log(b);}());ループの以下など、このアルゴリズムから変形している他のものがあります。私は他に何も話しません。
/***アレイ要素の順序をインプレースにランダム化します。* Durstenfeld Shuffle Algorithm。*/function shufflearray(array){for(var i = array.length-1; i> 0; i-){var j = math.floor(math.random()*()*(i + 1); var temp = array [i]; array [i]; temp;} return array;}ES2015(ES6)の使用
array.prototype.shuffle = function(){let m = this.length、i; while(m){i =(math.random() * m-)>>> 0; [this [m]、this [m]] = [this [m]]}これを返します;}使用:
[1、2、3、4、5、6、7] .shuffle();
中国の検索のために多くのランダムアルゴリズムを見つけましたが、それが完全にランダムであるかどうかはまだ必要であり、効率と互換性はまだ調査されます。後でアレイ要素をランダムに破壊する必要がある場合は、上記の要素を使用できることをお勧めします。