JavaScript 在空索引中壓入值到陣列


我們有一個數組,其中包含一些空值,如下所示:

const arr = [43,534534,645,64,,645,64,,645,,645,,65,,645,,64];

我們需要編寫一個數組函式 pushAtEmpty(),它接受一個元素,並將其推送到在上下文中使用的陣列中找到的第一個空索引。如果沒有任何空格,應該將元素推送到陣列的末尾。

我們來編寫此函式的程式碼。我們將首先搜尋空位置的索引,然後用我們提供的值替換那裡的值。

示例

const arr = [43,534534,645,64,,645,64,,645,,645,,65,,645,,64];
Array.prototype.pushAtEmpty = function(element){
   let index;
   for(index = 0; index < this.length; index++){
      if(arr[index] === undefined){
         this.splice(index, 1, element);
         break;
      };
   };
   if(index === this.length){
      this.push(element);
   }
};
arr.pushAtEmpty(23);
arr.pushAtEmpty(33);
arr.pushAtEmpty(43);
arr.pushAtEmpty(53);
arr.pushAtEmpty(63);
arr.pushAtEmpty(73);
arr.pushAtEmpty(83);
arr.pushAtEmpty(93);
console.log(arr);

輸出

控制檯中的輸出將為:

[
   43, 534534, 645, 64,
   23, 645, 64, 33,
   645, 43, 645, 53,
   65, 63, 645, 73,
   64, 83, 93
]

更新於:26-Aug-2020

1 千次 + 觀看

啟動您的職業生涯

完成課程認證

開始訪問
廣告
© . All rights reserved.