Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

JavaScript đẩy giá trị vào chỉ số trống trong mảng

Có mảng chứa giá trị trống (empty slots), viết phương thức mảng pushAtEmpty() nhận phần tử và đẩy vào chỉ số trống đầu tiên. Nếu không có chỗ trống, đẩy vào cuối.

Ví dụ

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);

Kết quả

Đầu ra trong console sẽ là:

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