For in loop issue with ember


#1

I am using for in (loop) in my javascript with ember js. It is returning all the methods which is attached to it prototype.

var a = [] for(i in a){console.log(i)}

it returns _super,nextObject,firstObject,lastObject, etc…

How can i eliminate it from for in loop?


#2

What you want is the following:

a.forEach(function(item, index){
  console.log(arguments);
});

Ember extends native objects hence all the methods attached. You can turn this behaviour off if you really need to. More info here: http://emberjs.com/api/classes/Ember.html#property_EXTEND_PROTOTYPES


#3

Even with prototypes disabled, you should not use for..in to loop on arrays. For…in is used to enumerate an object’s properties. It is then logical it also goes through lastObject and friends. You will also notice that for large arrays, depending on the browser, for..in does not loop in the order you would expect. That’s because properties are unordered.

There are only two correct ways to loop on an array:

An actual loop:

for (i = 0, n = a.length; i < n; i += 1) { console.log(a[i]; }

The forEach method that rytis suggested:

a.forEach(function (item) { console.log(item); });

(and the other functional-flavored methods, map, filter, every, …)

For reference, looping on object properties - including prototype properties:

for (key in obj) { console.log(key, obj[key]); }

Excluding prototype properties:

for (key in obj) { if (obj.hasOwnProperty(key) { console.log(key, obj[key]); } }

And as a bonus: getting all object’s property names, excluding prototype properties:

Object.keys(obj)

Remember that object properties are unordered. Therefore the order in which those will return the properties is unspecified and may even change on the same browser depending on the number of properties (chrome does that as tree optimization kicks in when the object reaches a specific size).


#4

Thanks for the reply