Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 these extra keys... unique last truncate random include contains any

Why?

like image 995
fancy Avatar asked Jan 19 '23 23:01

fancy


1 Answers

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.)

like image 129
Trevor Burnham Avatar answered Jan 21 '23 13:01

Trevor Burnham