Can I limit the length of an array in JavaScript?

前端 未结 6 1152
无人共我
无人共我 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:27

    I think you could just do:

    let array = [];
    array.length = 2;
    Object.defineProperty(array, 'length', {writable:false});
    
    
    array[0] = 1 // [1, undefined]
    
    array[1] = 2 // [1, 2]
    
    array[2] = 3 // [1, 2] -> doesn't add anything and fails silently
    
    array.push("something"); //but this throws an Uncaught TypeError
    

提交回复
热议问题