📜  js 从数组中删除 null - Javascript (1)

📅  最后修改于: 2023-12-03 15:32:22.393000             🧑  作者: Mango

JS 从数组中删除 null

在 JavaScript 中,有时候我们需要从数组中删除 null 值。这种情况通常出现在我们需要从服务器获取数据的时候,有些数据项可能为空,我们需要将这些空值从数组中删除。

以下是几种从数组中删除 null 的方法:

方法一:使用 filter 函数
let arr = [3, "hello", null, 5, null, "world"];
arr = arr.filter(item => item !== null);
console.log(arr); // [3, "hello", 5, "world"]

上面的代码使用数组的 filter 函数,匿名函数判断每个数组元素是否等于 null,如果不等于则保留,否则删除。最后,将过滤后的数组赋值给原数组。

方法二:使用 splice 函数
let arr = [3, "hello", null, 5, null, "world"];
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === null) {
    arr.splice(i, 1);
    i--;
  }
}
console.log(arr); // [3, "hello", 5, "world"]

上面的代码使用了数组的 splice 函数,循环遍历数组,如果当前元素等于 null,则使用 splice 函数移除该元素。需要注意的是,在使用 splice 函数之后需要将循环索引 i 减一,否则会漏删一个 null。

方法三:使用 reduce 函数
let arr = [3, "hello", null, 5, null, "world"];
arr = arr.reduce((accumulator, currentValue) => {
  if (currentValue !== null) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(arr); // [3, "hello", 5, "world"]

上面的代码使用数组的 reduce 函数,初始值为一个空数组,遍历数组中的每个元素,如果当前元素不等于 null 则将其添加到累加器 accumulator 中。最后返回累加器。

以上是三种从数组中删除 null 的方法,各有优劣。在实际应用中,可根据需求选择适合自己的方法。