简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM