views:

16

answers:

1

Can someone explain what's going on here, and how to fix it? I'm using JSMock, and executing the following code in spec.js:

for (var t in []) {
    alert(t)
}

... causes my browser to alert "eachIndexForJsMock" (when it shouldn't execute the alert command at all). This is messing up my for each loops. How do I fix it?

+1  A: 

The problem is that JSMock augments the Array.prototype object.

The for-in statement is meant to be used to enumerate object properties, for arrays and array-like1 objects, it is always recommended to use an iterative loop, e.g.:

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

You should avoid for-in on array-like objects because:

  • The order of iteration is not guaranteed, the indexes may not be visited in the numeric order.
  • Inherited properties are also enumerated.

See also:

[ 1 ] By array-like I mean any object that contains sequentially numbered properties and a length property.

CMS
See: [Loop through array in JavaScript](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript/3010848#3010848) for a more detailed explanation.
CMS
Wow, that's really unintuitive. In my opinion, there should at least be another `foreach` construct that behaves the way it would behave in other languages, such as PHP. Thanks for your answer though!
Chetan