JavaScript for…in vs for

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

    I second opinions that you should choose the iteration method according to your need. I would suggest you actually not to ever loop through native Array with for in structure. It is way slower and, as Chase Seibert pointed at the moment ago, not compatible with Prototype framework.

    There is an excellent benchmark on different looping styles that you absolutely should take a look at if you work with JavaScript. Do not do early optimizations, but you should keep that stuff somewhere in the back of your head.

    I would use for in to get all properties of an object, which is especially useful when debugging your scripts. For example, I like to have this line handy when I explore unfamiliar object:

    l = ''; for (m in obj) { l += m + ' => ' + obj[m] + '\n' } console.log(l);
    

    It dumps content of the whole object (together with method bodies) to my Firebug log. Very handy.

提交回复
热议问题