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

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


当前回答

由于没有其他人提到它,而且大多数人的项目中都包含下划线,因此您也可以使用_.without(array,*values);。

_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]

其他回答

这个呢(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"]

编辑:这个问题几乎在九年前就得到了回答,当时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,,,,]);

只需一个衬垫:

[1, false, "", undefined, 2].filter(Boolean); // [1, 2]

或使用underscorejs.org:

_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]

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

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

美好的很不错的我们也可以像这样替换所有数组值

Array.prototype.ReplaceAllValues = function(OldValue,newValue)
{
    for( var i = 0; i < this.length; i++ )  
    {
        if( this[i] == OldValue )       
        {
            this[i] = newValue;
        }
    }
};