javascript - js sets the maximum length of an array
高洛峰
高洛峰 2017-05-19 10:21:23
0
7
779

For example, if you set the maximum length of an array to 9, and delete it if it exceeds 9, what should you do?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(7)
小葫芦
//重写push方法
Array.prototype.push = function(o,capacity){
    var start = this.length;
    if(capacity && start>=capacity){
        this.pop();
        start--;
    }
    start = Math.max(start,0);
    this.splice(start,0,o);
    return this;
}
迷茫

Set arr.length=9 directly; no need to judge!

習慣沉默

Use arr.length to judge

阿神

if(arr.length > 9){

arr.splice(9, 1);

}

習慣沉默
if(arr.length>9){
    arr.length=9;
}

This ensures that the maximum length is 9

世界只因有你

I assume that your application scenario is to automatically detect the length when pushing elements into the array, and delete them after copying 9. Wouldn’t it be very rigid to call the detection method every time you push? I have an idea: rewrite the push method of array

巴扎黑

arr.length=9;

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template