开发者

Weird problem with JSMock

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 i开发者_如何学Ct 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.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:

  • Iteration VS Enumeration

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜