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

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


当前回答

就地解决方案:

function pack(arr) { // remove undefined values
  let p = -1
  for (let i = 0, len = arr.length; i < len; i++) {
    if (arr[i] !== undefined) { if (p >= 0) { arr[p] = arr[i]; p++ } }
    else if (p < 0) p = i
  }
  if (p >= 0) arr.length = p
  return arr
}

let a = [1, 2, 3, undefined, undefined, 4, 5, undefined, null]
console.log(JSON.stringify(a))
pack(a)
console.log(JSON.stringify(a))

其他回答

如果使用库是一个选项,我知道underscore.js有一个名为compact()的函数http://documentcloud.github.com/underscore/它还有其他几个与数组和集合相关的有用函数。

以下是他们文档的摘录:

_.compact(数组)返回删除了所有错误值的数组副本。在JavaScript中,false、null、0、“”、undefined和NaN都是假的。_.compact([0,1,false,2,'',3]);=> [1, 2, 3]

@阿尔尼塔克

实际上,如果您添加一些额外的代码,Array.filter可以在所有浏览器上运行。见下文。

var array = ["","one",0,"",null,0,1,2,4,"two"];

function isempty(x){
if(x!=="")
    return true;
}
var res = array.filter(isempty);
document.writeln(res.toJSONString());
// gives: ["one",0,null,0,1,2,4,"two"]  

这是您需要为IE添加的代码,但过滤器和函数式编程是值得的。

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}

您应该使用filter获取不含空元素的数组。ES6示例

const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);

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

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

只需一个衬垫:

[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]