簡體   English   中英

可以將空插槽推入陣列嗎?

[英]Possible to push empty slot to an array?

我正在建立自己的地圖方法,使其與本地地圖方法一樣接近。 由於本機映射將(我認為)更改后的值壓入一個新數組,因此它仍然保留空白插槽。 我無法找到將空插槽推入陣列的解決方案,如下面的示例所示。

[1, 2, 3].push(some code) // [1, 2, 3, empty]

我嘗試推送一個數組,該數組的一個空項目的前綴為散布運算符arr.push(...(new Array(1)))arr.push(...[,])但這只是推送undefined

我通過不使用push來解決問題 ,而是將值分配給數組索引,這樣跳過的索引將設置為空。

但是我正在寫這篇文章,以查看是否有人知道是否可以使用push方法將空插槽推入數組。

不,這是不可能的,不是push方法。 僅當數組具有特定長度時才可以存在empty ,但是數組的整數屬性在某個索引處不存在。 這稱為稀疏數組 ,不能通過push (或其他數組方法,如果它們是在非稀疏數組上調用的話)創建的。

這樣做的唯一方法是將其分配給尚不存在較低索引的索引。

在瀏覽器控制台而不是代碼段控制台中查看以下兩個代碼段的結果:

 const arr = []; arr[1] = 'a'; console.log(arr); 

或將數組的.length設置為該數組具有的最后一個索引上方:

 const arr = []; arr.length = 1; console.log(arr); 

但是上述兩種方法非常奇怪 ,可能沒有充分的理由使用。 最好完全避免稀疏數組。

請記住,空插槽不同於undefined ,它很可能具有數組值:

 const arr = []; arr.push(undefined); console.log(arr); 

您可以通過增加數組長度在數組中創建一個空插槽:

 var a = [] a.push(1) a.length++ a.push(3) console.log(a) console.log(1 in a) // anything at index 1? 

或者,您可以推送某些內容然后將其刪除:

 var a = [] a.push(1) a.push(2) a.push(3) delete a[1] console.log(a) console.log(1 in a) // anything at index 1? 

實際上,您無需在實現中推送到新數組。 您可以簡單地執行new Array(this.length) ,其中this.length是要通過長度映射的數組。

例如,考慮以下map實現:

 if (!Array.prototype.mapIt) { Object.defineProperty(Array.prototype, "mapIt", { value: function(fn) { if (this === null) { throw new TypeError('Array.prototype.mapIt called on null or undefined'); } if (typeof fn !== 'function') { throw new TypeError('predicate must be a function'); } let _array = this.filter(x => x != null) // remove empty values let result = new Array(_array.length) // the new array we will return for (var i = 0; i < _array.length; i++) { result[i] = fn.call(arguments[1], _array[i], i, _array) // call the predicate } return result; } }); } let arr = [1, 2, , , 3] // the test array let result = arr.mapIt((c, i, a) => console.log(`current: ${c}`, `index: ${i}`, `array: ${a}`) || c + 2) console.log('result: ', result) console.log('original array: ', arr) 

希望這對您有所幫助,讓您對可能的map實現有所了解。

暫無
暫無

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

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