如何在 JavaScript 中构建循环?

有帮助吗?

解决方案

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...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 循环遍历数组。它违背了 欧洲制造商协会262 标准,当将非标准属性或方法添加到 Array 对象时可能会导致问题,例如经过 原型. (谢谢 蔡斯塞伯特 在评论中指出这一点)

While 循环

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

其他提示

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

我们有一系列的物品 节点.

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

您还可以考虑优化循环速度;看 http://www.robertnyman.com/2008/04/11/javascript-loop-performance/

除了内置循环之外(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));

JavaScript 中的循环如下所示:

for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top