Limit array size

前端 未结 6 1805
隐瞒了意图╮
隐瞒了意图╮ 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 05:54

    Just adjust the length property after pushing.

    function add(x) {
        a.unshift(x);
        a.length = a.length < 7 ? a.length : 7;
    }
    

    The cleanes way is to check before

    function add(x) {
        a.unshift(x);
        if (a.length > 7) {
            a.length = 7;
        }
    }
    

提交回复
热议问题