javascript - for var index in vs. forEach -


in javascript, if want loop through every element in array, have several methods that:

1.

for(var =0; i<array.length; i++){} 

2.

array.foreach(function(item, index){}); 

3.

for (var index in array){} 

the first 1 common one, if feel lazy, want use second or third one.

but wonder if there's difference between them, , in situation should choose which?

they subtly different approaches.

for(var = 0; i<array.length; i++){} tried-and-true method; feels c, works c.

  • iterates on every array index, without corresponding property/item.
  • works on object supporting .length , properties names [0..length); while works on sparsely-populated arrays additional guard may required.
  • unlike foreach, allows use of continue/break/return manual adjustment of index within loop body, if such ever required.

array.foreach(function(item, index){}) approach prefer because sufficient, feels cleaner, , "lazy".

  • iterates on every array value/index that has property.
  • implicitly implies new function-scope each loop.
  • while defined on array.prototype it can used on array-like objects call/apply.
  • it has more overhead for..i++ (link stolen james g.'s comment). however, doesn't matter , relative performance difference decrease work done in body increases.

for (var index in array){} should not used when dealing array/sequence iteration.

  • iterates on all not-excluded-from-enumeration properties, traversing [prototype] well
  • property names iterated in implementation-defined order2

here demonstration of differences:

var array = []; array[0] = 1; array[2] = 2;  // note `1 in array` false never set array.hello_world = 3;  var = 0; for(var = 0; i<array.length; i++){     += array[i] } // -> nan; because array[1] undefined console.log("index: " + a);  var b = 0; array.foreach(function (v, i) {     b += v; }); // -> 3; because v never undefined (as array[1] skipped) console.log("foreach: " + b);  var c = 0; (var p in array) {     c += array[p]; } // -> 6; picked "hello_world" didn't pick missing "1" property console.log("for..in: " + c);  

2 example producing different iteration order between browsers:

var = []; (var = 100000; > 0; -= 1000) { a[i] = i; }  var s = ""; (var p in a) { s += p + ",";  } console.log(s); 

chrome , ie 10 iterate in ascending numerically; ff iterates in order inserted (for smaller ranges of values firefox sorts ascending numerically). don't use approach iterating sequence , there won't problems this.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -