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

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


当前回答

第一个例子是,当使用上面投票最高的答案时,我得到的字符串长度大于1的单个字符。下面是我解决这个问题的方法。

var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});

如果未定义,则不返回,如果长度大于0,则返回。希望这能帮助一些人。

退换商品

["some string yay", "Other string yay"]

其他回答

var a = [{a1: 1, children: [{a1: 2}, undefined, {a1: 3}]}, undefined, {a1: 5}, undefined, {a1: 6}]
function removeNilItemInArray(arr) {
    if (!arr || !arr.length) return;
    for (let i = 0; i < arr.length; i++) {
        if (!arr[i]) {
            arr.splice(i , 1);
            continue;
        }
        removeNilItemInArray(arr[i].children);
    }
}
var b = a;
removeNilItemInArray(a);
// Always keep this memory zone
console.log(b);

我只是在上面的“用全局构造函数调用ES5的数组..filter()”高尔夫技巧中添加了我的声音,但我建议使用Object而不是上面建议的String、Boolean或Number。

具体来说,ES5的filter()已经不会为数组中未定义的元素触发;因此,一个普遍返回true(返回所有元素filter()命中)的函数必然只返回未定义的元素:

> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]

然而,写出。。。(function(){return true;})的长度大于写入。。。(对象);在任何情况下,Object构造函数的返回值都将是某种类型的对象。与上面建议的基本装箱构造函数不同,没有可能的对象值是假的,因此在布尔设置中,object是function(){return true}的缩写。

> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]

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

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

另一种方法是利用数组的长度属性:将非空项打包到数组的“左侧”,然后减少长度。它是一种就地算法-不分配内存,对垃圾收集器来说太糟糕了-并且它具有非常好的最佳/平均/最坏情况行为。

与这里的其他解决方案相比,这个解决方案在Chrome上速度快2到50倍,在Firefox上速度快5到50倍http://jsperf.com/remove-null-items-from-array

下面的代码将不可枚举的“removeNull”方法添加到Array中,该方法为菊花链返回“this”:

var removeNull = function() {
    var nullCount = 0           ;
    var length    = this.length ;
    for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }
    // no item is null
    if (!nullCount) { return this}
    // all items are null
    if (nullCount == length) { this.length = 0; return this }
    // mix of null // non-null
    var idest=0, isrc=length-1;
    length -= nullCount ;                
    while (true) {
         // find a non null (source) slot on the right
         while (!this[isrc])  { isrc--; nullCount--; } 
         if    (!nullCount) { break }       // break if found all null
         // find one null slot on the left (destination)
         while ( this[idest]) { idest++  }  
         // perform copy
         this[idest]=this[isrc];
         if (!(--nullCount)) {break}
         idest++;  isrc --; 
    }
    this.length=length; 
    return this;
};  

Object.defineProperty(Array.prototype, 'removeNull', 
                { value : removeNull, writable : true, configurable : true } ) ;

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