4

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.

8
  • 1
    Have you tried changing it ? Commented Jun 22, 2016 at 7:22
  • Could you just hardcode them to return 2? Commented Jun 22, 2016 at 7:24
  • i tried but in vain @Rayon,yes i want that value to be 2 or anything but it should be same value for any array. Commented Jun 22, 2016 at 7:36
  • @bharathmuppa, Read array.length Commented Jun 22, 2016 at 7:40
  • 2
    "I got an idea to override javascript array length value" - wrong idea. What are you actually trying to do? Commented Jun 22, 2016 at 8:55

1 Answer 1

2

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.

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

2 Comments

"Array.length is a protected property, only read; is a bad idea try to change it." No it is not protected, it can be modified and depending on the case it is a pretty good idea to change it such as emptying an array without breaking its references by making it's length = 0;
You can change the value, like b.length = 2; (and delete the last value), but not to change is behaviour, like Array.prototype.length = 2;. Maybe I expressed inexactly.

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.