在相当长的一段时间里,我一直有这样的印象:for
循环可能存在solely采用以下格式:
for (INITIALIZER; STOP CONDITION; INC(DEC)REMENTER)
{
CODE
}
然而,这是最绝对事实并非如此;看看这个 JavaScript 实现费舍尔-耶茨洗牌 http://en.wikipedia.org/wiki/Knuth_shuffle:
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
陈述。如果有人能够提供一个相对彻底的解释来解释这个巫术到底是如何做它所做的事情,那就太好了。提前非常感谢。
shuffle = function(o){
for (
var j, // declare j
x, // declare x
i = o.length; // declare i and set to o.length
i; // loop while i evaluates true
j = parseInt(Math.random() * i), // j=random number up to i
x = o[--i], // decrement i, and look up this index of o
o[i] = o[j], // copy the jth value into the ith position
o[j] = x // complete the swap by putting the old o[i] into jth position
);
return o;
};
这是从 i 等于位置数开始,每次交换卡片 i 和 j,其中 j 是每次到 i 的某个随机数,根据算法。
它可以写得更简单,没有令人困惑的逗号集,true。
顺便说一句,这是notJavaScript 中唯一一种 for 循环。还有:
for(var key in arr) {
value = arr[key]);
}
但要小心,因为这也会循环访问对象的属性,包括您传入 Array 对象的情况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)