0

I noticed that whenever i modify an array prototype it changes the behavior of foreachs. I have created the example below to show you guys what im doing:

Array.prototype.x = 10;
for(var i in [1,2,3]){
    alert(i);
}

This example shows four alerts: "1", "2", "3" and "x";

Why this code give me 4 alerts?

How can i modify array prototype without interfere with the foreach ?

2
  • 2
    Of course! You add one more enumerable property to all array instances. Why are you surprised? Commented Jul 12, 2014 at 14:50
  • It is generally considered a bad idea to use a for/in loop for arrays. Stick to using for/in with objects, and a regular for loop for arrays. However, you can extend Array.prototype without making the extensions enumerable; see bfontaine's correct answer below. Commented Jul 12, 2014 at 14:53

1 Answer 1

2

You need to define your property as “non-enumerable”:

Object.defineProperty(Array.prototype, 'x', {
    enumerable: false,
    value: 10
});

Here is a JSFiddle that shows the code in action.

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.