如何在JavaScript中构建循环?

时间:2008-09-09 14:55:10

标签: javascript loops

如何在JavaScript中构建循环?

5 个答案:

答案 0 :(得分:26)

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 loops

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
}

答案 1 :(得分:1)

以下是for循环的示例:

我们有一系列项目节点

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

答案 2 :(得分:1)

答案 3 :(得分: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));

答案 4 :(得分:-1)

JavaScript中的循环如下所示:

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