如何在JavaScript中建立循环?
对于循环
1 2 3 4 5
| 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
} |
对于...在循环中
1 2 3 4 5
| 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循环在数组上进行操作是一种不好的做法。它违反ECMA 262标准,并且在将非标准属性或方法添加到Array对象时,例如,可能会导致问题。通过原型。
(感谢Chase Seibert在评论中指出了这一点)
While循环
1 2 3
| while (myCondition) {
// The loop will continue until myCondition is false
} |
您也可以考虑优化循环速度;参见http://www.robertnyman.com/2008/04/11/javascript-loop-performance/
这是一个for循环的示例:
我们有一个项目节点数组。
1 2 3 4
| for(var i = 0; i< nodes.length; i++){
var node = nodes[i];
alert(node);
} |
除了内置循环(while() ...,do ... while(),for() ...)之外,还有一种自调用函数的结构,也称为递归,可以创建没有三个内置循环结构的循环。
考虑以下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| // 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 + '');
// decrease the loopCounter, to prevent running forever
loopCounter--;
// test loopCounter and if truthy call loop() again
loopCounter && loop();
}
// invoke the loop
loop(); |
不用说,此结构通常与返回值结合使用,因此这是一个小例子,说明如何处理不是首次可用但在递归结束时可用的值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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)); |
JavaScript中的循环如下所示:
1 2 3
| for (var = startvalue; var <= endvalue; var = var + increment) {
// code to be executed
} |