如何填充数组中的空位?

Mou*_*ier 0 javascript arrays

我正在寻找用[,,]的值填充数组中的空白点null。如果有 2 个,,我需要 3 个元素

我也希望它能在数组如下所示的情况下工作:[value,,][, value,][,,value]

if (Object.values(row).length !== row.length) {
  let newRow: any[];
  newRow = row.map(el => {
    if (el) {
      return el;
    } else {
      return 'null';
    }
  });
  console.log('newRow:: ', newRow);
  return newRow;
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*mar 7

首先,您可以从Array.from创建一个新数组,然后添加null(如果有)empty slot

注意:您必须明确检查索引是否存在

(!(i in arr)) // if index is present in whole prototype chain
Run Code Online (Sandbox Code Playgroud)

因为可能存在这样的情况:您已经定义了一个值,undefined然后您必须跳过该值以将其覆盖为 null。

假设您有一个数组,[, undefined, ,]然后您想排除undefined索引处的值1

(!(i in arr)) // if index is present in whole prototype chain
Run Code Online (Sandbox Code Playgroud)
function fillEmptySlotsWithNull(arr) {
  return Array.from(arr, (_, i) => {
    if (!(i in arr)) return null;
    else return arr[i];
  });
}

const inputs = [
  [, , , ],
  [, undefined, , ],
  ["value", , ],
  [, "value"],
  [, , "value"],
];

inputs.forEach((input) => {
  const result = fillEmptySlotsWithNull(input);
  console.log(result);
});
Run Code Online (Sandbox Code Playgroud)

您还可以使用 oldfor-loop也作为:

/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
Run Code Online (Sandbox Code Playgroud)
function fillEmptySlotsWithNullWithForLoop(arr) {
    const result = [];
    for (let i = 0; i < arr.length; ++i) {
        if (!(i in arr)) result.push(null);
        else result.push(arr[i])
    }
    return result;
}

const inputs = [
  [, , , ],
  [, undefined, , ],
  ["value", , ],
  [, "value"],
  [, , "value"],
];

inputs.forEach((input) => {
  const result = fillEmptySlotsWithNullWithForLoop(input);
  console.log(result);
});
Run Code Online (Sandbox Code Playgroud)