Search code examples
javascriptarraysprototype-programming

Javascript - Prototyped Function Name Returned As A Key Of Associative Array


I'm wanting to add a prototyped function to javascript's array object.

The problem I'm having is that when I step the keys of an array, the prototyped function's name appears in the array's keys.

Here's a sample to illustrate the problem:

<html>
  <head>
    <script type="text/javascript">
      Array.prototype.foo = function () {
        // do something
      }
      function keys() {
        var fruit = ["apples","pears","bannanas"];
        for (key in fruit) alert(key); // alerts: 0, 1, 2, foo
      }
    </script>
  </head>
  <body onload="keys();">
  </body>
</html>

Any ideas on how I can get around this?

I don't have to prototype the function but, from a readability point of view, I'd prefer to.

EDIT: Just to be clear, the real world implementation of the above example iterates through an associative array, hence the for..in loop

EDIT: Thanks for the replies guys but I think you're missing what I'm after. What I'm wanting to know is whether I can add a prototyped function to javascript's array object (or declare the function in a different way that would have the same effect) without having the function name pitch up while iterating through an array via a for..in loop. Take the indexOf function for example. Javascript seems to define it internally in such a way that it doesn't appear in the keys of the object/array (right?). Can this same behaviour be reproduced at runtime?


Solution

  • I appreciate it isn't always available but you can avoid the whole mess by using Array#forEach or if you're using a JavaScript library (quite likely and highly recommended) then you have something like Prototype's Enumerable#each(), Sugar's Array#each() or jQuery's $.each().