2008-09-09 26 views
5

如何在JavaScript中構建循環?如何在JavaScript中構建循環?

+0

有人正在搞亂SO,downvoting很多東西,看起來... – 2008-09-09 15:09:23

+0

啊。那麼我想我在用戶發言中對這件事的咆哮有點激動了。 – UnkwnTech 2008-09-09 15:11:45

回答

24

For循環

for (i = startValue; i <= endValue; i++) { 
    // Before the loop: i is set to startValue 
    // After each iteration of the loop: i++ is executed 
    // The loop continues as long as i <= endValue is true 
} 

對於...在循環

for (i in things) { 
    // If things is an array, i will usually contain the array keys *not advised* 
    // If things is an object, i will contain the member names 
    // Either way, access values using: things[i] 
} 

這是不好的做法,使用for...in循環來itterate了數組。它違背了ECMA 262標準,並且可能會在將非標準屬性或方法添加到Array對象時導致問題,例如,通過Prototype(感謝Chase Seibert在評論指出這一點)

While循環

while (myCondition) { 
    // The loop will continue until myCondition is false 
} 
-1

在JavaScript中循環如下所示:

for (var = startvalue; var <= endvalue; var = var + increment) { 
    // code to be executed 
} 
1

這裏是一個循環的一個例子:

我們有一個項目節點的數組。

for(var i = 0; i< nodes.length; i++){ 
    var node = nodes[i]; 
    alert(node); 
} 
0

除了形成疊合在環(while() ...do ... while()for() ...),有自呼叫功能的結構,也被稱爲遞歸創建沒有三個疊合在環結構的環。

考慮以下幾點:

// set the initial value 
 
var loopCounter = 3; 
 

 
// the body of the loop 
 
function loop() { 
 

 
    // this is only to show something, done in the loop 
 
    document.write(loopCounter + '<br>'); 
 

 
    // decrease the loopCounter, to prevent running forever 
 
    loopCounter--; 
 

 
    // test loopCounter and if truthy call loop() again 
 
    loopCounter && loop(); 
 
} 
 

 
// invoke the loop 
 
loop();

不用說,這種結構是在一個返回值組合經常使用的,所以這是一個小例子如何處理值,不是在第一次可用,而是在遞歸結束時:

function f(n) { 
 
    // return values for 3 to 1 
 
    //  n -n ~-n !~-n +!~-n return 
 
    // conv int neg bitnot not number 
 
    //  3 -3 2 false 0 3 * f(2) 
 
    //  2 -2 1 false 0 2 * f(1) 
 
    //  1 -1 0  true 1  1 
 
    // so it takes a positive integer and do some conversion like changed sign, apply 
 
    // bitwise not, do logical not and cast it to number. if this value is then 
 
    // truthy, then return the value. if not, then return the product of the given 
 
    // value and the return value of the call with the decreased number 
 
    return +!~-n || n * f(n - 1); 
 
} 
 

 
document.write(f(7));