Can I Limit The Length Of An Array In JavaScript?
Answer :
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
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);
arr.length = Math.min(arr.length, 5)
Comments
Post a Comment