search

Home  >  Q&A  >  body text

javascript - js sets the maximum length of an array

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

高洛峰高洛峰2837 days ago827

reply all(7)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:23:23

    //重写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;
    }

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:23:23

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

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:23:23

    Use arr.length to judge

    reply
    0
  • 阿神

    阿神2017-05-19 10:23:23

    if(arr.length > 9){

    arr.splice(9, 1);

    }

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:23:23

    if(arr.length>9){
        arr.length=9;
    }

    This ensures that the maximum length is 9

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:23:23

    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

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:23:23

    arr.length=9;

    reply
    0
  • Cancelreply