如何在JavaScript中建立循环?

时间:2020-03-05 18:50:06  来源:igfitidea点击:

如何在JavaScript中建立循环?

解决方案

回答

JavaScript中的循环如下所示:

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

回答

这是一个for循环的示例:

我们有一个item节点数组。

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

回答

对于循环

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 (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循环

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

回答

我们也可以考虑优化循环速度;参见http://www.robertnyman.com/2008/04/11/javascript-loop-performance/