JavaScript 将值推送到数组中的空索引中

javascriptweb developmentobject oriented programming更新于 2025/10/12 19:56:17

我们有一个数组,其中包含一些空值,如下所示 −

const arr = [43,534534,645,64,,645,64,,645,,645,,645,,645,,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
]

相关文章


有用资源