JavaScript for…in vs for

前端 未结 22 1191
悲哀的现实
悲哀的现实 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:26

    There is an important difference between both. The for-in iterates over the properties of an object, so when the case is an array it will not only iterate over its elements but also over the "remove" function it has.

    for (var i = 0; i < myArray.length; i++) { 
        console.log(i) 
    }
    
    //Output
    0
    1
    
    for (var i in myArray) { 
        console.log(i) 
    } 
    
    // Output
    0 
    1 
    remove
    

    You could use the for-in with an if(myArray.hasOwnProperty(i)). Still, when iterating over arrays I always prefer to avoid this and just use the for(;;) statement.

提交回复
热议问题