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.