我可以在JavaScript中限制数组的长度吗? [英] Can I limit the length of an array in JavaScript?

查看:2980
本文介绍了我可以在JavaScript中限制数组的长度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示产品浏览历史记录,因此我将产品ID存储在浏览器Cookie中。

I want to display the product browsing history, so I am storing the product ids in a browser cookie.

由于历史记录列表仅限于5个项目,我将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.

我想问如何限制数组长度,以便它只能存储5个项目?

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

如何在数组索引4之后剪切项目?

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: '/' });
}


推荐答案

正确:

arr.splice(4, 1)

这会从索引4移除1个项目。请参阅此处

this will remove 1 item at index 4. see here

我想要使用切片

arr.slice(0,5)

这假设您的所有代码(Cookie等)都能正常工作

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

这篇关于我可以在JavaScript中限制数组的长度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆