如何在JavaScript中构建循环?

Unk*_*ech 7 javascript loops

如何在JavaScript中构建循环?

geo*_*ock 27

对于循环

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
}
Run Code Online (Sandbox Code Playgroud)

对于......循环

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]
}
Run Code Online (Sandbox Code Playgroud)

使用for...in循环来迭代数组是不好的做法.它违反了ECMA 262标准,并且当非标准属性或方法添加到Array对象时会导致问题,例如Prototype. (感谢Chase Seibert在评论中指出这一点)

循环

while (myCondition) {
    // The loop will continue until myCondition is false
}
Run Code Online (Sandbox Code Playgroud)

  • 你不应该使用for ...来循环数组.这将导致Prototype出现问题.见http://www.prototypejs.org/api/array (2认同)
  • 如果使用hasOwnProperty进行检查,可以避免使用for-in循环的问题:if(!things.hasOwnProperty(i)){continue; } (2认同)