2

I added unique() function to Javascript Array:

Array.prototype.unique = function(){
  return this.filter(function(item, ind, arr){
    return ind == arr.lastIndexOf(item);
  });
};

but when I iterate like this:

for (i in arr) { ... }

i becomes unique as well:

var arr = [1, 2, 1];
for (i in arr) {
    console.log(i + " ===> " + arr[i]);
}

// 0 ===> 1
// 1 ===> 2
// 2 ===> 1
// unique ===> function () { return this.filter(function (item, ind, arr) {return ind == arr.lastIndexOf(item);}); }

I know that I can iterate like this:

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

However, I still wonder if it's possible to add functions to Array and iterate like this:

for (i in arr) { ... }

?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • 4
    you should not use for in when operating with an array http://stackoverflow.com/a/6974628/575527 – Joseph Mar 18 '12 at 11:26
  • Similar: [Javascript custom Array.prototype interfering with for-in loops](http://stackoverflow.com/questions/1529593/javascript-custom-array-prototype-interfering-with-for-in-loops), [JavaScript “For …in” with Arrays](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) – minopret Mar 18 '12 at 11:36

1 Answers1

5

You can make the unique property non-enumerable.

Object.defineProperty(Array.prototype, "unique", { enumerable : false,
                                                  configurable : true});
taskinoor
  • 45,586
  • 12
  • 116
  • 142