簡體   English   中英

Javascript - 如何強制數組具有特定數量的元素

[英]Javascript - How can i force an array to have a specific amount of elements

是否有一種簡單的方法可以使數組具有特定數量的元素。 從某種意義上說,如果你向它推進更多,它會覆蓋第一個元素。

例如,我希望一個數組只包含2個元素。 如果我推第三個元素,它應該覆蓋最早的元素(第一個)。 像堆棧一樣。

您可以使用計數器並使用具有所需長度的模數進行插入。

 function push(array, length) { var counter = 0; return function (value) { array[counter % length] = value; counter++; }; } var array = [], pushToArray = push(array, 2); pushToArray(1); console.log(array); pushToArray(2); console.log(array); pushToArray(3); console.log(array); pushToArray(4) console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

所以我上面已經評論過你可以通過數組子類來做到這一點。 以下代碼片段引入了一個新的Array結構,其中包含兩個新方法作為lastpush 然而,我們的新push影響Array.prototype的真正push方法。 push取第一個參數作為數組長度的限制,如[1,2,3].push(4,"a","b","c")將長度限制為4,結果將是[3,"a","b","c"] 返回值將是數組中已刪除的元素,因為我們在引擎蓋下使用splice

 function SubArray(...a) { Object.setPrototypeOf(a, SubArray.prototype); return a; } SubArray.prototype = Object.create(Array.prototype); SubArray.prototype.last = function() { return this[this.length - 1]; }; SubArray.prototype.push = function(lim,...a){ Array.prototype.push.apply(this,a); return this.splice(0,this.length-lim); }; myArray = new SubArray(1,2,3); myArray.last(); myArray.push(4,"a","b","c"); console.log(myArray); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM