如何限制数组值的数量?

时间:2017-04-24 14:07:31

标签: javascript jquery arrays performance

我有一个JS数组,它的每个键都包含一个页面的整个HTML。我将该数组用作后退前进按钮。

有时当它包含100页的HTML时,浏览器的性能会下降。我有两个问题:

  1. 我可以计算内存中JS数组的大小吗?
  2. 如何限制数组?我的意思是,当我推送新值时,我想删除旧数组的值。事情的例子。
  3. 当前数组:

    var myarr = ['val1', 'val2', 'val3']; // - it should be limited to 3 values
    +------+------+------+
    | val1 | val2 | val3 |
    +------+------+------+
    

    将新值推入其中后的预期数组:

    myarr.push('val4'); // expected result:
    
    +------+------+------+
    | val2 | val3 | val4 |
    +------+------+------+
    

    这样做可能吗?

2 个答案:

答案 0 :(得分:0)

显然你想要一种堆栈。如果您正在使用此数组,并且多次调用例如。您可以替换它的推送功能(不是Array.prototype,而是推送实例本身)。在那里你可以限制数组并在需要时移动元素。

var push = arrayInstance.push;
arrayInstance.push = function(elem) {
    // todo check length and remove leading elems if needed
    push(elem);
}

它可能在语法上不正确但你掌握了。这不是一个干净的解决方案,更好的方法是嵌套功能并创建一个相应的对象/类。

答案 1 :(得分:0)

为什么甚至使用数组。如果您正在动态构建作为PREVIOUS和NEXT页面的HTML的数组的值,那么您是否只是拥有为您保存这些值的全局变量?

lastPage = HTML of currentPage-1
thisPage = HTML of currentPage
nextPage = HTML of currentPage +1

所以当你前进......

lastPage = thisPage;
thisPage = nextPage;
nextPage = HTML of currentPage + 1 (computed)

然后回来......

nextPage = thisPage;
thisPage = lastPage;
lastPage = HTML of currentPage -1 (computed)

这样就不会有阵列增长或内存泄漏问题。