JavaScript for…in vs for

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

    Note that the native Array.forEach method is now widely supported.

    0 讨论(0)
  • 2020-11-22 07:38

    I have seen problems with the "for each" using objects and prototype and arrays

    my understanding is that the for each is for properties of objects and NOT arrays

    0 讨论(0)
  • 2020-11-22 07:39

    I'd use the different methods based on how I wanted to reference the items.

    Use foreach if you just want the current item.

    Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)

    I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题