JavaScript for…in vs for

2018-12-31 09:57发布

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 arrays:

var myArray = [{'key': 'value'}, {'key': 'value1'}];

So we can iterate:

for (var i = 0; i < myArray.length; i++)

And:

for (var i in myArray)

I don't see a big difference. Are there any performance issues?

标签: javascript
23条回答
只靠听说
2楼-- · 2018-12-31 10:17

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.

查看更多
临风纵饮
3楼-- · 2018-12-31 10:17

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.
}
查看更多
墨雨无痕
4楼-- · 2018-12-31 10:18

here is something i did.

function foreach(o, f) {
 for(var i = 0; i < o.length; i++) { // simple for loop
  f(o[i], i); // execute a function and make the obj, objIndex available
 }
}

this is how you would use it
this will work on arrays and objects( such as a list of HTML elements )

foreach(o, function(obj, i) { // for each obj in o
  alert(obj); // obj
  alert(i); // obj index
  /*
    say if you were dealing with an html element may be you have a collection of divs
  */
  if(typeof obj == 'object') { 
   obj.style.marginLeft = '20px';
  }
});

I just made this so I'm open to suggestions :)

查看更多
春风洒进眼中
5楼-- · 2018-12-31 10:18

If you really want to speed up your code, what about that?

for( var i=0,j=null; j=array[i++]; foo(j) );

it's kinda of having the while logic within the for statement and it's less redundant. Also firefox has Array.forEach and Array.filter

查看更多
若你有天会懂
6楼-- · 2018-12-31 10:19

there are performance differences depending on what kind of loop you use and on what browser.

For instance:

for (var i = myArray.length-1; i >= 0; i--)

is almost twice as fast on some browsers than:

for (var i = 0; i < myArray.length; i++)

However unless your arrays are HUGE or you loop them constantly all are fast enough. I seriously doubt that array looping is a bottleneck in your project (or for any other project for that matter)

查看更多
只靠听说
7楼-- · 2018-12-31 10:19

For in loops on Arrays is not compatible with Prototype. If you think you might need to use that library in the future, it would make sense to stick to for loops.

http://www.prototypejs.org/api/array

查看更多
登录 后发表回答