Limit array size

前端 未结 6 1820
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 05:25

Let\'s say I have an array with data elements, in this example numbers, like this:

var a = [432, 238, 122, 883, 983];

And I want to limit t

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 06:00

    You can check the length of array when adding and Shift it (remove the first element) if the length has passed:

    function add(x) {
        a.push(x);
        if (a.length > 7)
            a.shift();
    }
    

提交回复
热议问题