bharath muppa
bharath muppa

Reputation: 1079

override array length in javascript

I got an idea to override javascript array length value and wants to return any random value.
let's say..

 a=[56,78,89,200,800]
 b=['a','b','f']

 a.length = 2  ;  //should give me only 2;
 b.length = 2  ; //also should give 2  

Is it possible to change length property and is there any tweaks to change the splice or slice method also.

Upvotes: 4

Views: 2292

Answers (1)

José M. Carnero
José M. Carnero

Reputation: 263

Array.length is a protected property, only read; is a bad idea try to change it.

Better you can create your own class; example:

var oArray = function (aArr){
    oRet = {};

    for(var i = 0, aArrL = aArr.length; i < aArrL; i++){
        oRet[i] = aArr[i];
    }
    oRet.length = 2;

    return oRet;
};

a= new oArray([56,78,89,200,800]);
b=['a','b','f'];

console.log(a.length);
console.log(b.length);

a is a custom class, b is standard JavaScript Array.

Upvotes: 2

Related Questions