Sandy
Sandy

Reputation: 2613

Add property to javascript Array similar to length

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?

Upvotes: 3

Views: 545

Answers (1)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

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.

Upvotes: 6

Related Questions