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?
The problem is that JSMock augments the
Array.prototypeobject.The
for-instatement 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.:You should avoid
for-inon array-like objects because:See also:
[ 1 ] By array-like I mean any object that contains sequentially numbered properties and a
lengthproperty.