如何在 JavaScript 中构建循环?
如何在 JavaScript 中构建循环?
IT技术
javascript
loops
                    2021-02-08 17:38:27
                
                    
                
            
        5个回答
            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循环来迭代数组是不好的做法。它违反ECMA 262标准,并且在将非标准属性或方法添加到 Array 对象(例如通过Prototype )时可能会导致问题。
(感谢Chase Seibert在评论中指出这一点)
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);
}
除了内置循环(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
}
其它你可能感兴趣的问题