[ACCEPTED]-Javascript: hiding prototype methods in for loop?-for-loop

Accepted answer
Score: 62

You can achieve desired outcome from the 6 other end by making the prototype methods 5 not enumerable:

Object.defineProperty(Array.prototype, "containsKey", {
  enumerable: false,
  value: function(obj) {
      for(var key in this)
        if (key == obj) return true;
      return false;
    }
});

This usually works better 4 if you have control over method definitions, and 3 in particular if you have no control over 2 how your code will be called by other people, which 1 is a common assumption in library code development.

Score: 57

You can use JavaScript's hasOwnProperty method to achieve 1 this in the loop, like this:

for(var key in arr) {
    if (arr.hasOwnProperty(key)) {
        ...
    }
}

Reference: This YUI blog article.

Score: 4

Javascript doesn't support associative arrays 6 the way you think they do. http://ajaxian.com/archives/javascript-associative-arrays-considered-harmful

for (var i in 5 .. gets all of the properties of an object 4 (an array is just another object) which 3 is why you're seeing the other objects you've 2 prototyped to it.

As the article suggests 1 you should use an object:


var assoc = {'One' : 1, 'Two' : 2};
assoc['Three'] = 3;

for(var key in assoc)
   alert(key+' => '+assoc[key]);
Score: 3

you could do this:

for(var key in arr)
{
   if (typeof(arr[key]) == "function")
      continue;
   alert(key);
}

But that's a shoddy workaround

0

Score: 2

You can hide methods that added to prototype 3 from for-in loops like this:

Object.defineProperty(Array.prototype, "containsKey", { enumerable: false });

Just after you 2 add method. where the "containsKey" is 1 your added method.

Score: 1

Method 1: use Object.keys (which doesn't return prototype properties) & loop

Object.keys(arr); // ['One', 'Two', 'Three']
Object.keys(arr).forEach(key => console.log(key))

Method 2: hasOwnProperty inside 1 a for-loop.

 for(var key in arr) {
   if (arr.hasOwnProperty(key)) {
     ...
   }
 }
Score: 0

For high-performance iteration over JavaScript 6 arrays, use either a for or while loop. Nicholas 5 Zakas discusses the most-performant options 4 for iterating over arrays in his Tech Talk 3 Speed Up Your JavaScript.

Your best bet is probably something like 2 this:

for (var i = collection.length - 1; i >= 0; i--) {
  if (obj == collection[i]) return true;
}

This approach will be peform best for 1 a few reasons:

  • Only a single local variable is allocated
  • The collection's length property is only accessed once, at the initialization of the loop
  • Each iteration, a local is compared to a constant (i >= 0) instead of to another variable

More Related questions