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

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


当前回答

编辑:这个问题几乎在九年前就得到了回答,当时Array.prototype中没有太多有用的内置方法。

现在,当然,我建议您使用过滤方法。

请记住,此方法将返回一个新数组,其中包含传递给它的回调函数的条件的元素。

例如,如果要删除空值或未定义的值:

var array=[0,1,null,2,“”,3,undefined,3,,,,4,,,5,,6,,,];var filtered=array.filter(函数(el){返回el!=无效的});console.log(已过滤);

这取决于你认为什么是“空”的。例如,如果你处理字符串,上面的函数不会删除空字符串的元素。

我经常看到的一个典型模式是删除错误的元素,其中包括空字符串“”、0、NaN、null、undefined和false。

您可以传递给筛选方法、布尔构造函数或返回筛选条件函数中的相同元素,例如:

var filtered = array.filter(Boolean);

Or

var filtered = array.filter(function(el) { return el; });

在这两种情况下,这都是有效的,因为在第一种情况下过滤器方法将布尔构造函数作为函数调用,转换值,而在第二种情况下过滤方法在内部将回调的返回值隐式转换为布尔值。

如果您正在使用稀疏数组,并且正在尝试消除“空洞”,则可以使用filter方法传递返回true的回调,例如:

var spareArray=[0,,1,,,2,,3],cleanArray=sparseArray.filter(函数(){return true});console.log(cleanArray);//[ 0, 1, 2, 3 ]

老答案:不要这样做!

我使用这个方法,扩展了本机Array原型:

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);

或者您可以简单地将现有元素推入其他数组:

// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
  var newArray = new Array();
  for (var i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);

其他回答

带下划线/Loddash:

一般使用情况:

_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);

有空:

_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]

无需参阅lodash文档。

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

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

下面是一个使用变量行为和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"];

这个呢(ES6):从数组中删除Falsy值。

var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];

arr.filter((v) => (!!(v)==true));

//output:

//[1, 2, "test", "false", true, 3, 4, 5, "end"]

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

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