在Javascript中删除数组中的空元素

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

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


我使用这种方法,扩展了本地数组的原型:

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,,,,]);

简单的方法:

var arr = [1,2,,3,,3,null,,0,,undefined,4,,4,,5,,6,,,,];

// (filter - JS 1.6 and above)
arr = arr.filter(function(n){ return n != undefined }); 

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]

//or - (only for arrays items which are numbers is numbers' strings)**
arr = arr.filter(Number) // [1, 3, 3, 4, 4, 5, 6]

// ES6 style (Firefox FTW)
arr.filter(n => true) // [1, 2, 3, 3, null, 0, undefined, 4, 4, 5, 6]

// or if "null" values are to be removed:
arr.filter(n => n)

或 - (仅适用于“文本”类型的单个数组项)

['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); 
// output:  ["1","2","3","4","5"]

或 - 传统方式:简单迭代

var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
    len = arr.length, i;

for(i = 0; i < len; i++ )
    arr[i] && arr.push(arr[i]);  // copy non-empty values to the end of the array

arr.splice(0 , len);  // cut the array and leave only the non-empty values

arr // [1,2,3,3,[],Object{},5,6]


通过jQuery:

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

arr = $.grep(arr,function(n){ return n == 0 || n });

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]


更新 - 另一种快速,酷炫的方式(使用ES6):

var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,], 
    temp = [];

for(let i of arr)
    i && temp.push(i); // copy each non-empty value to the 'temp' array

arr = temp;
delete temp; // discard the variable

arr // [1, 2, 3, 3, 4, 4, 5, 6]

删除空值

['foo', '',, ' ', true, [], [1], {}, undefined].filter(String)

// ["foo", " ", true, [1], Object {}, undefined]

删除错误的值

另一种删除空字符串"" ,“ 0和“ undefined """falsey"值的方法

[1, 2,, 3,, 3,undefined,,"",false,null,0,NaN, 4," ", 4,true, 5,, 6,,,,].filter(Boolean);

// [1, 2, 3, 3, 4, " ", 4, true, 5, 6]

如果您需要删除所有空值(“”,null,undefined和0):

arr = arr.filter(function(e){return e}); 

删除空值和换行符:

arr = arr.filter(function(e){ return e.replace(/(rn|n|r)/gm,"")});

例:

arr = ["hello",0,"",null,undefined,1,100," "]  
arr.filter(function(e){return e});

返回:

["hello", 1, 100, " "]

更新(基于Alnitak的评论)

在某些情况下,您可能希望在数组中保留“0”并除去其他任何内容(null,undefined和“”),这是一种方法:

arr.filter(function(e){ return e === 0 || e });

返回:

["hello", 0, 1, 100, " "]
链接地址: http://www.djcxy.com/p/981.html

上一篇: Remove empty elements from an array in Javascript

下一篇: NDepend: How to not display 'tier' assemblies in dependency graph?