2017-04-24 135 views
-1

我有一個JS數組,它的每個鍵都包含一個頁面的整個HTML。我使用該陣列作爲返回轉發按鈕。如何限制數組值的數量?

有時,當它包含100頁的HTML時,瀏覽器的性能會下降。那麼我有兩個問題:

  1. 是否有可能計算內存上的JS數組的大小?
  2. 如何限制數組?我的意思是,當我推送新值時,我想刪除舊數組的值。例如打擊。

當前數組:

myarr.push('val4'); // expected result: 

+------+------+------+ 
| val2 | val3 | val4 | 
+------+------+------+ 

是這樣做可能:

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

推新值之後預計陣?

+2

使用[Array.prototype.shift()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)刪除第一個元素。 – Danmoreng

+0

如果您知道如何使用array.slice,您可以創建一個所需長度的新數組:var arr2 = [... myarr.slice(-2),...)使用方法yourArrayInsertCustomMethod(item)來管理數組邏輯 – ferflores

+0

, 'var4']' – maioman

回答

0

顯然你想要一種堆棧。如果你有這個數組已經在使用,並且有很多調用push的例子。你可以替換它的推送函數(不是Array.prototype,而是推送實例本身)。在那裏你可以限制數組並在需要時移動元素。

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

它可能在語法上不正確,但你得到了把握。這不是一個乾淨的解決方案,更好的方法是嵌套功能並創建相應的對象/類。

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) 

這樣就不會有任何陣列生長或內存泄漏問題。