Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the "size" property to Javascript Array?

Tags:

javascript

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

like image 945
Misha Moroshko Avatar asked Dec 28 '22 21:12

Misha Moroshko


2 Answers

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.

like image 51
Anurag Avatar answered Jan 10 '23 13:01

Anurag


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.

like image 34
alex Avatar answered Jan 10 '23 12:01

alex