2016-11-29 8 views
0

私はそうのようなループのための標準で、これらの要素にアクセスして一覧表示することが可能です知っている配列forループを使用して、配列内のすべての要素にランダムにアクセスできますか?

var array = ["what","is","going","on"]; 

あります

for (i = 0; i <= array.length; i++) { 
    console.log(array[i]); 
    } 

しかし、私はこれらのリストを表示する方法はありますかどうかを知りたいと要素をランダムな順序で返します。私は数学のいくつかのバリエーションを使用しなければならないと思う。私は確かにどちらを使うべきかを決めるのに十分な経験がありません。前もって感謝します!

答えて

0

まず、配列をシャッフルして1つずつ読み込む必要があります。 Array.prototype.shuffle()のような配列メソッドが便利かもしれません。

Array.prototype.shuffle = function(){ 
 
    var i = this.length, 
 
     j, 
 
    tmp; 
 
    while (i > 1) { 
 
    j = Math.floor(Math.random()*i--); 
 
    tmp = this[i]; 
 
    this[i] = this[j]; 
 
    this[j] = tmp; 
 
    } 
 
    return this; 
 
}; 
 

 
var arr = [1,2,3,4,5].shuffle(); 
 
for(var i = 0; i < arr.length; i++) console.log(arr[i]);

0

話して統計的には、これは間違いなく動作します。それは完了するために宇宙の熱 - 死までにかかります。

var array = ["What", "am", "I", "doing", "with", "my", "life"]; 
 
var processed = []; 
 

 
function randomAccess() { 
 
    if (processed.length === array.length) { 
 
    console.log('Done!'); 
 
    return; 
 
    } 
 
    
 
    var index = Math.floor(Math.random() * array.length); 
 
    if (processed.indexOf(index) === -1) { 
 
    // Make sure we haven't processed this one before 
 
    console.log('array[' + index + ']:', array[index]); 
 
    processed.push(index); 
 
    } 
 
    // Prevent locking up the browser 
 
    setTimeout(randomAccess, 0); 
 
} 
 
randomAccess();

生産コードでこれを使用しないでください。理論的には、それは決して完了しないかもしれない。

0

はい、同じインデックスを複数回返さないように、ランダムに返されたインデックスを記録するために2番目の配列を導入することができます。

の作業例:

var myArray = ['what','is','going','on']; 
 
var returnedIndices = []; 
 

 
for (i = 0; i < myArray.length; i++) { 
 

 
    var randomIndex = Math.floor(Math.random() * myArray.length); 
 

 
    if (returnedIndices.indexOf(randomIndex) !== -1) { 
 
     i--; 
 
     continue; 
 
    } 
 

 
    else { 
 
     returnedIndices[i] = randomIndex; 
 
     console.log(myArray[randomIndex]); 
 
    } 
 
}

+1

オーケーありがとう皆。 Math.floorとMath.randomの組み合わせが必要です。 – mujiha

+0

'Math.floor(Math.random()* n)'は、JavaScriptが '0'と' n'の間の乱数を生成する標準的な方法です。 。 'Math.random'は' 0'と '1'の間にランダムな浮動小数点を生成します。 'Math.floor'はfloatを最も近い整数に丸めます。例: '0.35856 * 6 = 2.15136'これは「2」に切り下げられます。 – Rounin

0

console.log(array[Math.floor(Math.random() * (array.length - 1))]);

関連する問題