JavaScript for…in vs for

前端 未结 22 1134
悲哀的现实
悲哀的现实 2020-11-22 07:15

Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?

Let\'s say we have an array of associative array

22条回答
  •  隐瞒了意图╮
    2020-11-22 07:34

    The two are not the same when the array is sparse.

    var array = [0, 1, 2, , , 5];
    
    for (var k in array) {
      // Not guaranteed by the language spec to iterate in order.
      alert(k);  // Outputs 0, 1, 2, 5.
      // Behavior when loop body adds to the array is unclear.
    }
    
    for (var i = 0; i < array.length; ++i) {
      // Iterates in order.
      // i is a number, not a string.
      alert(i);  // Outputs 0, 1, 2, 3, 4, 5
      // Behavior when loop body modifies array is clearer.
    }
    

提交回复
热议问题