我可以在 JavaScript 中限制数组的长度吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14236515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:07:16  来源:igfitidea点击:

Can I limit the length of an array in JavaScript?

javascriptjquerycookies

提问by Charles Yeung

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

我想显示产品浏览历史记录,因此我将产品 ID 存储在浏览器 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.

由于历史列表限制为5个项目,我将cookie值转换为数组,然后检查它的长度并删除多余的。

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?

我想问一下如何限制数组长度使其只能存储5个项目?

Or

或者

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

如何在数组索引 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: '/' });
}

回答by Samuele Mattiuzzo

You're not using splice correctly:

您没有正确使用 splice:

arr.splice(4, 1)

this will remove 1 item at index 4. see here

这将删除索引 4 处的 1 个项目。请参见此处

I think you want to use slice:

我想你想使用slice

arr.slice(0,5)

this will return elements in position 0 through 4.

这将返回位置 0 到 4 的元素。

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

这假设您的所有其余代码(cookie 等)都正常工作

回答by justspamjustin

arr.length = Math.min(arr.length, 5)

回答by fregante

The fastestand simplest way is by setting the .lengthproperty to the desired length:

最快和最简单的方法是通过设置.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 = 4will add two undefineditems to it. Perhaps add a condition:

警告:设置此属性还可以使数组比实际长度更长:如果其长度为 2,则运行arr.length = 4会为其添加两个undefined项目。也许添加一个条件:

if (arr.length > 4) arr.length = 4;

Alternatively:

或者:

arr.length = Math.min(arr.length, 4);

回答by Luche

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

这个解决方案在像 p5js 这样的动态环境中效果更好。我把它放在绘图调用中,它动态地限制了数组的长度。

The problem with:

问题在于:

arr.slice(0,5)

...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

...是每个并条机仅从阵列中取出固定数量的项目,如果您的用户可以添加多个项目,则无法保持阵列大小不变。

The problem with:

问题在于:

if (arr.length > 4) arr.length = 4;

...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

...是它从数组的末尾删除项目,因此如果您还使用 push() 添加到末尾,则不会循环遍历数组。

回答by jfriend00

You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.

从其中删除项目后,您需要实际使用缩短的数组。您忽略了缩短的数组。

You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).

您将 cookie 转换为数组。你减少了数组的长度,然后你永远不会使用那个缩短的数组。相反,您只需使用旧的 cookie(未缩短的 cookie)。

You should convert the shortened array back to a string with .join(",")and then use it for the new cookie instead of using old_cookiewhich is not shortened.

您应该将缩短的数组转换回字符串,.join(",")然后将其用于新的 cookie,而不是使用old_cookie未缩短的字符串。

You may also not be using .splice()correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice()here.

您可能也没有.splice()正确使用,但我不确切知道您缩短数组的目标是什么。您可以在.splice()此处阅读有关确切功能的信息

回答by La Secta

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