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: '/' }); }
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 .
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.
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.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With