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

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


当前回答

如果使用库是一个选项,我知道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;
  };
}

要移除孔,应使用

arr.filter(() => true)
arr.flat(0) // New in ES2019

对于删除孔、空和未定义:

arr.filter(x => x != null)

用于删除hole和falsy(null,undefined,0,-0,0n,NaN,“”,false,document.all)值:

arr.filter(x => x)

arr=[,null,(void 0),0,-0,0n,NaN,false,“”,42];console.log(arr.filter(()=>true));//[null,(void 0),0,-0,0n,NaN,false,“”,42]console.log(arr.filter(x=>x!=null));//[0,-0,0n,NaN,假,“”,42]console.log(arr.filter(x=>x));//[42]

注:

孔是一些没有元素的数组索引。

arr = [, ,];
console.log(arr[0], 0 in arr, arr.length); // undefined, false, 2; arr[0] is a hole
arr[42] = 42;
console.log(arr[10], 10 in arr, arr.length); // undefined, false, 43; arr[10] is a hole

arr1 = [1, 2, 3];
arr1[0] = (void 0);
console.log(arr1[0], 0 in arr1); // undefined, true; a[0] is undefined, not a hole

arr2 = [1, 2, 3];
delete arr2[0]; // NEVER do this please
console.log(arr2[0], 0 in arr2, arr2.length); // undefined, false; a[0] is a hole

上述所有方法都返回给定数组的副本,而不是就地修改它。

arr = [1, 3, null, 4];
filtered = arr.filter(x => x != null);
console.log(filtered); // [1, 3, 4]
console.log(arr); // [1, 3, null, 4]; not modified

只需一个衬垫:

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

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

删除所有空元素

如果数组包含空对象、数组和字符串以及其他空元素,我们可以使用以下方法删除它们:

const arr=[[],['not','empty'],{},{key:'value'},0,1,null,2,“”,“here”,“”3,undefined,3,,,4,4,5,6,,]let filtered=JSON.stringify(arr.filter((obj)=>{回来[null,未定义,“”]。includes(obj)}).filter((el)=>{返回类型el!=“object”||对象.键(el).长度>0}))console.log(JSON.parse(已过滤))

简单压缩(从数组中删除空元素)

使用ES6:

常量arr=[0,1,null,2,“”,3,未定义,3,,,4,4,5,6,,]let filtered=arr.filter((obj)=>{return!〔null,undefined〕.includes(obj)})console.log(已过滤)

使用纯Javascript->

var arr=[0,1,null,2,“”,3,未定义,3,,,4,4,5,6,,]var filtered=arr.filter(函数(obj){return!〔null,undefined〕.includes(obj)})console.log(已过滤)