3

Is it possible to add property to javascript Array like length which do not get iterated over in For IN loop, but have different value for each instance created

Following code:

a = new Array();
a.dimension = 2; //add a new property to array

Here if in case for in loop is used to iterate a, dimension will also be iterated which I don't want.

Is this possible to add such property?

0

1 Answer 1

6

Yes, it's possible. Use defineProperty -

Object.defineProperty(a, "dimension", {
    enumerable: false,
    configurable: true,
    writable: true,
    value: 2
});

This will create a property called dimension for a which will not be enumerated in the for..in loop.

You can define a function for creating properties like this -

function defineArrayProperties(object, property, value) {
    Object.defineProperty(object, property, {
        enumerable: false,
        configurable: true,
        writable: true,
        value: value
    });
}

and then you can call it like this -

var b = [];
defineArrayProperties(b, "dimension", 3);

You can also create this function in the Array prototype and let all array objects inherit it by default -

Array.prototype.defineProperty = function (property, value) {
    Object.defineProperty(this, property, {
        enumerable: false,
        configurable: true,
        writable: true,
        value: value
    });
};

var b = [];
b.defineProperty("dimension", 4);
alert(b.dimension);   // will alert 4

A Live Fiddle is here demonstrating both of the above approaches. I have created two array objects and enumerated all of their properties using for...in. Notice that dimension doesn't show up in any of the for...in.

EDIT

Your browser must support ECMAScript 5 in order for Object.defineProperty to work properly.

Sign up to request clarification or add additional context in comments.

2 Comments

fails in for in loop, I still get dimension iterated var arr = new Array(); Object.defineProperty(arr, "dimension", { enumerable: false, configurable: true, writable: true, value: 2 }); for (a in arr){ console.log(a);} //prints dimension
my bad...had added _dim to prototype somewhere in my code which was causing this...fixed that and it worked fine ..thanks a lot

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.