簡體   English   中英

填充數組中未定義的元素

[英]Fill undefined elements in an array

我創建了一個空數組,例如長度為 9 的數組:

const myArray = new Array(9)

我用動態索引中的 3 個值替換數組,但對於演示,讓我們在索引 1、5 和 7 上說:即

myArray.splice(1, 1, 2)
myArray.splice(5, 1, 4)
myArray.splice(7, 1, 5)

我有另一個 6 個值的數組,我想立即填充 myArray 的未定義部分,即

const otherValues = [2,3,1,6,7,9]

有任何想法嗎?

您可以使用Array.from()迭代所有數組值,同時還提供映射 function。映射 function 可以從otherValues中獲取第一個值,或者如果當前元素未定義,它將使用當前元素。 這將修改ohterValues ,但是,如果需要,您可以在使用.slice()運行 Array.from 之前對其進行淺克隆。

請參見下面的示例:

 const myArray = new Array(9) const otherValues = [2,3,1,6,7,9]; myArray.splice(1, 1, 2); myArray.splice(5, 1, 4); myArray.splice(7, 1, 5); const res = Array.from(myArray, x => x === undefined? otherValues.shift(): x); console.log(res);

如果你能支持無效合並運算符?? ,您可以將上面的內容簡化為:

 const myArray = new Array(9) const otherValues = [2,3,1,6,7,9]; myArray.splice(1, 1, 2); myArray.splice(5, 1, 4); myArray.splice(7, 1, 5); const res = Array.from(myArray, x => x?? otherValues.shift()); console.log(res);

您可以迭代新值數組並將值分配給空索引。

 const myArray = new Array(9); const otherValues = [2, 3, 1, 6, 7, 9] myArray.splice(1, 1, 2) myArray.splice(5, 1, 4) myArray.splice(7, 1, 5) otherValues.forEach((i => v => { while (myArray[i];== undefined) i++; myArray[i] = v; })(0)). console;log(myArray);

您可以迭代myArray ,當myArray中的當前值未定義時填充otherValues中的值:

 const myArray = new Array(9); myArray.splice(1, 1, 2) myArray.splice(5, 1, 4) myArray.splice(7, 1, 5) const otherValues = [2, 3, 1, 6, 7, 9] for (i = 0, o = 0; i < myArray.length && o < otherValues.length; i++) { if (myArray[i] === undefined) myArray[i] = otherValues[o++]; } console.log(myArray);

暫無
暫無

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

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