Can I limit the length of an array in JavaScript?

前端 未结 6 1196
无人共我
无人共我 2020-12-25 09:50

I want to display the product browsing history, so I am storing the product ids in a browser cookie.

Because the list of history is limited to 5 items, I convert the

6条回答
  •  梦毁少年i
    2020-12-25 10:05

    var  arrLength = arr.length;
    if(arrLength > maxNumber){
        arr.splice( 0, arrLength - maxNumber);
    }
    

    This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

    The problem with:

    arr.slice(0,5)
    

    ...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

    The problem with:

    if (arr.length > 4) arr.length = 4;
    

    ...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

提交回复
热议问题