我發現這個代碼在網上洗牌數組元素,它工作得很好,但我不能在這裏瞭解for
環洗牌數組元素
shuffle = function(o)
{
for(var j, x, i = o.length; i;
j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
任何幫助表示讚賞,謝謝!
我發現這個代碼在網上洗牌數組元素,它工作得很好,但我不能在這裏瞭解for
環洗牌數組元素
shuffle = function(o)
{
for(var j, x, i = o.length; i;
j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
任何幫助表示讚賞,謝謝!
這基本上是錯誤的for
循環的靈活性。
用於for
循環的一般語法:
for (<init>; <condition>; <increment>) {
<body>
}
這大致可表示爲以下while
循環:
<init>;
while(<condition>) {
<body>
<increment>
}
由於兩個<body>
和<increment>
都執行就好像它們是在身體的while
,任何可以進入for
循環體的東西,也可以放在<increment>
快車for
循環的離子。你只需要用逗號而不是分號分隔語句。
因此您for
循環可能是更好的表述如下while
循環:
var j, x, i = o.length;
while (i) { // same as while(i != 0)
j = parseInt(Math.random() * i);
x = o[--i];
o[i] = o[j];
o[j] = x;
}
j = parseInt(Math.random() * i); // Getting a random number between 0 to n-1, where n is the length of the array.
x = o[--i]; // Getting the last element of the array and storing it in a variable.
o[i] = o[j]; // Storing the randomly selected index value at the last position.
o[j] = x; // Storing the last element's value in random position.
i值將在每次循環迭代遞減並且它將替換最後然後倒數然後等等...並與阿雷內的隨機元件陣列的finallly第一個元素。
問題是關於循環,而不是語句的邏輯.. – Abcd 2011-05-13 12:52:53
哦,對不起,我以錯誤的方式得到了:) – 2011-05-13 12:53:55
我認爲這是[費雪耶茨算法(http://en.wikipedia.org/wiki/Fisher%E2% 80%93Yates_shuffle)帶有一些不可讀的編碼風格。 – 2011-05-13 12:38:51