4

To add the size() method to the Array object I do:

if (!Array.size) {
    Array.prototype.size = function() {
        return this.length;
    };
}

Is there a simple way to define the size property that will work like length ?

(I don't really need it, I just want to understand if this is something easily achievable in Javascript.)

3 Answers 3

8

With ES5 it's possible. Add a size property on the Array prototype,

Object.defineProperty(Array.prototype, "size", {
    get: function() {
        return this.length;
    },
    set: function(newLength) {
        this.length = newLength;
    }
});

var x = [1, 2, 3];
x.length    // 3
x.size      // 3

x.push(4);
x           // [1, 2, 3, 4]
x.length    // 4
x.size      // 4

x.length = 2;
x           // [1, 2]
x.size = 1;
x           // [1]

It basically works as a wrapper around length. Appears like a property to the naked eye, but is backed by an underlying function.

Thanks to @Matthew's comment, this size property works like a complete wrapper around length.

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

2 Comments

You could add a setter that changes this.length too.
@Matthew - that's a good idea, I just wanted to keep this example minimal.
1

I'll assume you already know this is not a real life issue.

length property is modified to suit the size of the array and reflected by methods such as shift() and pop().

So, you would need a method to get the length property.

Anurag shows you how it can be done with ES5.

Comments

1
if(!Array.size)
{
    Array.prototype.__defineGetter__('size', function(){
        return this.length;
    });
}

var a = new Array();
a.push(1);
a.push(4);

console.log(a.size);

Although I'm not entirely sure how cross-browser friendly that is (should work on Chrome and FF at least).

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.