如何在JavaScript中删除数组中的空元素?

是否有一种简单的方法,或者我需要循环并手动删除它们?


当前回答

下面是一个使用变量行为和ES2015胖箭头表达式的示例:

Array.prototype.clean = function() {
  var args = [].slice.call(arguments);
  return this.filter(item => args.indexOf(item) === -1);
};

// Usage
var arr = ["", undefined, 3, "yes", undefined, undefined, ""];
arr.clean(undefined); // ["", 3, "yes", ""];
arr.clean(undefined, ""); // [3, "yes"];

其他回答

“误用”。。。在(对象成员)循环中。=>循环体中仅显示真实值。

// --- Example ----------
var field = [];

field[0] = 'One';
field[1] = 1;
field[3] = true;
field[5] = 43.68;
field[7] = 'theLastElement';
// --- Example ----------

var originalLength;

// Store the length of the array.
originalLength = field.length;

for (var i in field) {
  // Attach the truthy values upon the end of the array. 
  field.push(field[i]);
}

// Delete the original range within the array so that
// only the new elements are preserved.
field.splice(0, originalLength);

试试这个。将数组传递给它,它将返回并删除空元素*更新以解决Jason指出的错误

function removeEmptyElem(ary) {
    for (var i = ary.length - 1; i >= 0; i--) {
        if (ary[i] == undefined)  {
            ary.splice(i, 1);
        }       
    }
    return ary;
}

要从数组中删除未定义的元素,只需使用

常量数组=[{name:“tim”,年龄:1},未定义,{姓名:“ewrfer”,年龄:22岁},{姓名:“3tf5gh”,年龄:56},无效的{姓名:“kygm”,年龄:19岁},未定义,];console.log(array.filter(布尔));

要移除孔,应使用

arr.filter(() => true)
arr.flat(0) // New in ES2019

对于删除孔、空和未定义:

arr.filter(x => x != null)

用于删除hole和falsy(null,undefined,0,-0,0n,NaN,“”,false,document.all)值:

arr.filter(x => x)

arr=[,null,(void 0),0,-0,0n,NaN,false,“”,42];console.log(arr.filter(()=>true));//[null,(void 0),0,-0,0n,NaN,false,“”,42]console.log(arr.filter(x=>x!=null));//[0,-0,0n,NaN,假,“”,42]console.log(arr.filter(x=>x));//[42]

注:

孔是一些没有元素的数组索引。

arr = [, ,];
console.log(arr[0], 0 in arr, arr.length); // undefined, false, 2; arr[0] is a hole
arr[42] = 42;
console.log(arr[10], 10 in arr, arr.length); // undefined, false, 43; arr[10] is a hole

arr1 = [1, 2, 3];
arr1[0] = (void 0);
console.log(arr1[0], 0 in arr1); // undefined, true; a[0] is undefined, not a hole

arr2 = [1, 2, 3];
delete arr2[0]; // NEVER do this please
console.log(arr2[0], 0 in arr2, arr2.length); // undefined, false; a[0] is a hole

上述所有方法都返回给定数组的副本,而不是就地修改它。

arr = [1, 3, null, 4];
filtered = arr.filter(x => x != null);
console.log(filtered); // [1, 3, 4]
console.log(arr); // [1, 3, null, 4]; not modified

可以使用带有索引和in运算符的筛选器

设a=[1,,2,,,3];设b=a.filter((x,i)=>a中的i);console.log({a,b});