JavaScript for…in vs for

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

    The choice should be based on the which idiom is best understood.

    An array is iterated using:

    for (var i = 0; i < a.length; i++)
       //do stuff with a[i]
    

    An object being used as an associative array is iterated using:

    for (var key in o)
      //do stuff with o[key]
    

    Unless you have earth shattering reasons, stick to the established pattern of usage.

提交回复
热议问题