9

如何在 JavaScript 中构建循环?

4

4 回答 4

29

对于循环

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...in 循环

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 对象(例如通过Prototype )时可能会导致问题。 (感谢Chase Seibert在评论中指出这一点)

While 循环

while (myCondition) {
    // The loop will continue until myCondition is false
}
于 2008-09-09T15:05:00.387 回答
1

下面是一个 for 循环的例子:

我们有一个 items节点数组。

for(var i = 0; i< nodes.length; i++){
    var node = nodes[i];
    alert(node);
}
于 2008-09-09T14:57:59.640 回答
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));

于 2015-09-02T14:27:40.170 回答
-1

JavaScript 中的循环如下所示:

for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
于 2008-09-09T14:55:34.373 回答