2011-05-13 75 views
1

我发现这个代码在网上洗牌数组元素,它工作得很好,但我不能在这里了解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; 
}; 

任何帮助表示赞赏,谢谢!

+1

我认为这是[费雪耶茨算法(http://en.wikipedia.org/wiki/Fisher%E2% 80%93Yates_shuffle)带有一些不可读的编码风格。 – 2011-05-13 12:38:51

回答

3

这基本上是错误的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; 
} 
2
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第一个元素。

+0

问题是关于循环,而不是语句的逻辑.. – Abcd 2011-05-13 12:52:53

+0

哦,对不起,我以错误的方式得到了:) – 2011-05-13 12:53:55