如何在JavaScript中構建循環?如何在JavaScript中構建循環?
5
A
回答
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);
}
1
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));
相關問題
- 1. 在JavaScript構建HTML模板循環
- 2. 在JavaScript中如何循環
- 3. 構建onclick內部循環Javascript/jquery
- 4. 如何在循環中創建循環(雙循環)
- 5. Javascript如何構建循環與非共享時間的迭代
- 6. 如何在R中構建for循環,我可能要循環零次?
- 7. 如何循環在JavaScript
- 8. 如何在golang中的列表中構建一個循環
- 9. 在循環中構建字典。 Python
- 10. 在循環中構建數組
- 11. 如何創建的javascript內部循環
- 12. Javascript:在For循環中創建函數
- 13. 在JavaScript中創建永久循環
- 14. 在javascript中創建JSON的循環
- 15. 在for循環中創建對象javascript
- 16. 在javascript中創建動畫循環(canvas)
- 17. 如何在javascript中循環這個?
- 18. 如何在Javascript中循環XMLHttpRequest
- 19. 如何在Javascript中循環函數?
- 20. 如何在JavaScript中打破foreach循環?
- 21. 如何在JavaScript中循環聲音?
- 22. 如何在Javascript中循環代碼
- 23. 如何在javascript中循環兩次?
- 24. 如何在javascript中循環訪問xmlhttprequest
- 25. 如何在JavaScript中執行循環?
- 26. 如何在javascript中的無限循環
- 27. 如何在javascript中設置循環
- 28. 如何在JavaScript中使用循環?
- 29. 如何在Javascript中循環不同部分的循環
- 30. 如何在foreach循環中構建HTML以包含輸出
有人正在搞亂SO,downvoting很多東西,看起來... – 2008-09-09 15:09:23
啊。那麼我想我在用戶發言中對這件事的咆哮有點激動了。 – UnkwnTech 2008-09-09 15:11:45