限制数组大小 [英] Limit array size

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

问题描述

假设我有一个包含数据元素的数组,在此示例中为数字,如下所示:

Let's say I have an array with data elements, in this example numbers, like this:

var a = [432, 238, 122, 883, 983];

我想限制数组,这样每当我向数组添加一个元素时,它总是保持长度为7或更小,并删除最旧的元素。

And I want to limit the array, so that everytime I add an element to the array, it always keeps a length of let's say 7, or less and removes the oldest elements.

我目前的aproach看起来像这样:

My current aproach looks like this:

function add(x) {
    a.unshift(x);
    a = a.slice(0, 7);
}

它运作得很好但是没有更优雅的方法可以做它,像一行或什么?

It works just fine, but isn't there a more elegant way to do it, like one line or something?

编辑:
更优雅我是说我不需要添加功能而且很容易内联我需要它的代码,没有输入例如三次,只有一行也会使代码更清晰

By "more elegant" I mean so that I don't need the add function and just easily could inline the code where I need it, without typing out a for example three times, and only having one line would also make the code "clearer"

推荐答案

只是添加另一种可能的选择:

Just to add another possible alternative:

a = [x, ...a.slice(0, 6)];

即使我个人选择 Nina Scholz 解决方案(改变长度的更好条件对于不支持ES6的旧环境)

Even though I would personally choose Nina Scholz's solution (with a "better" condition for changing length and for older environments where ES6 is not supported)

参考文献:


  • < a href =https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator =noreferrer> Spread operator

  • Spread operator

这篇关于限制数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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