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

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


当前回答

以上答案都不适用于所有类型。下面的解决方案将删除null、undefined、{}[]、NaN,并保留日期字符串,最好的是它甚至从嵌套对象中删除。

function removeNil(obj) {
    // recursively remove null and undefined from nested object too.
    return JSON.parse(JSON.stringify(obj), (k,v) => {
      if(v === null || v === '') return undefined;
      // convert date string to date.
      if (typeof v === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(v))
        return new Date(v);
      // remove empty array and object.
      if(typeof v === 'object' && !Object.keys(v).length) return undefined;
      return v;
    });
  }

函数removeNil(obj){//递归地从嵌套对象中删除null和undefined。返回JSON.parse(JSON.stringify(obj),(k,v)=>{如果(v===null||v==='')返回undefined;//将日期字符串转换为日期。if(typeof v==“string”&&/^\d\d\d\d-\d\dT\dd:\d\d:\d\d.d.d\dZ$/.test(v))返回新日期(v);//删除空数组和对象。if(typeof v=='object'&&!object.keys(v).length)返回undefined;返回v;});}常量ob={s: “a”,b: 43中,国家:['a','b','c'],l: 空,n: {ks:“a”,efe:null,ce:“”},d: new Date(),nan:nan,k: 未定义,emptyO:{},emptyArr:[],}常量输出=removeNil(ob);console.log(输出);console.log('测试:',ob.countries.length,typeof(ob.d))

其他回答

@阿尔尼塔克

实际上,如果您添加一些额外的代码,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;
  };
}

如果您有Javascript 1.6或更高版本,您可以使用Array.filter,使用简单的return true回调函数,例如:

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

因为.filter会自动跳过原始数组中缺少的元素。

上面链接的MDN页面还包含一个很好的错误检查版本的过滤器,可以在不支持官方版本的JavaScript解释器中使用。

注意,这不会删除空条目,也不会删除具有显式未定义值的条目,但OP特别请求“缺少”条目。

第一个例子是,当使用上面投票最高的答案时,我得到的字符串长度大于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"]

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

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

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

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