Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I limit the length of an array in JavaScript?

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 cookie value to an array, then check the length of it and cut the redundant.

The code below is what I have tried, but it does not work; the array item isn't removed.

I would like to ask how to limit the array length so it can only store 5 items?

Or

How can I cut the items after the array index 4?

var id = product_id; var browseHistory = $.cookie('history'); if (browseHistory != null) {   var old_cookie = $.cookie('history');   var new_cookie = '';    if (old_cookie.indexOf(',') != -1) {     var arr = old_cookie.split(',');     if (arr.length >= 5) {       arr.splice(4, 1)     }   }    new_cookie = id + ',' + old_cookie;   $.cookie('history', new_cookie, { expires: 7, path: '/' }); } else {   $.cookie('history', id, { expires: 7, path: '/' }); } 
like image 432
Charles Yeung Avatar asked Jan 09 '13 13:01

Charles Yeung


People also ask

How do you restrict the length of an array?

To limit array size with JavaScript, we can use the array slice method. to define the add function that takes an array a and value x that we prepend to the returned array. We keep the returned array the same size as a by calling slice with 0 and a. length - 1 to discard the last item in a .

Can you change the length of an array in JavaScript?

JavaScript allows you to change the value of the array length property. By changing the value of the length, you can remove elements from the array or make the array sparse.

How do you shorten an array in JavaScript?

In JavaScript, there are two ways of truncating an array. One of them is using length property and the other one is using splice() method.

How do I limit array length in typescript?

position: Array<number>; ...it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length i.e. 3 for x,y,z components can you make a type with for a fixed length array, something like this? Any help or clarification appreciated!


1 Answers

You're not using splice correctly:

arr.splice(4, 1) 

this will remove 1 item at index 4. see here

I think you want to use slice:

arr.slice(0,5) 

this will return elements in position 0 through 4.

This assumes all the rest of your code (cookies etc) works correctly

like image 121
Samuele Mattiuzzo Avatar answered Oct 09 '22 08:10

Samuele Mattiuzzo