开发者

for i of foo is returning extra keys?

I am calling this on an array with 3 objects in it. It ends up returning the correct keys in addition to th开发者_Python百科ese extra keys... unique last truncate random include contains any

Why?


You're getting those extra properties because you, or a library you're using, has extended the Array prototype. As Mike points out in his answer, you can skip those by using hasOwnProperty. Indeed, CoffeeScript has an own keyword built in that does this for you:

for own i of foo
  obj = foo[i]
  ...

But, as Mike also points out in his answer, it's more efficient to loop through an array by incrementing a counter rather than iterating over the keys. To do that, you'd use CoffeeScript's for...in syntax:

for obj in foo
  ...

(If you need indices in the loop as well, you can write for obj, i in foo.)


for (... in ...) will return things on the object's prototype. See JavaScript for...in vs for

The best solution is to iterate over array elements using an index loop

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

This has the benefit of getting a numeric key instead of a string and reliably iterating in order.

Alternatively, you can use hasOwnProperty to make sure you don't get keys from the prototype.

for (var k in obj) {
  if (!obj.hasOwnProperty(k)) { continue; }
  ...
}

or a variation if you're worried about hasOwnProperty being a overridden.

Even more alternatively, you can define these prototype properties as enumerable: false using Object.defineProperty.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜