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

?

2

1 Answer 1

5

You can make the unique property non-enumerable.

Object.defineProperty(Array.prototype, "unique", { enumerable : false,
                                                  configurable : true});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.