Can I limit the length of an array in JavaScript?

前端 未结 6 1205
无人共我
无人共我 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条回答
  •  无人及你
    2020-12-25 10:18

    The fastest and simplest way is by setting the .length property to the desired length:

    arr.length = 4;
    

    This is also the desired way to reset/empty arrays:

    arr.length = 0;
    

    Caveat: setting this property can also make the array longer than it is: If its length is 2, running arr.length = 4 will add two undefined items to it. Perhaps add a condition:

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

    Alternatively:

    arr.length = Math.min(arr.length, 4);
    

提交回复
热议问题