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

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


当前回答

要从数组中删除未定义的元素,只需使用

常量数组=[{name:“tim”,年龄:1},未定义,{姓名:“ewrfer”,年龄:22岁},{姓名:“3tf5gh”,年龄:56},无效的{姓名:“kygm”,年龄:19岁},未定义,];console.log(array.filter(布尔));

其他回答

这可能会帮助您:https://lodash.com/docs/4.17.4#remove

var details = [
            {
                reference: 'ref-1',
                description: 'desc-1',
                price: 1
            }, {
                reference: '',
                description: '',
                price: ''
            }, {
                reference: 'ref-2',
                description: 'desc-2',
                price: 200
            }, {
                reference: 'ref-3',
                description: 'desc-3',
                price: 3
            }, {
                reference: '',
                description: '',
                price: ''
            }
        ];

        scope.removeEmptyDetails(details);
        expect(details.length).toEqual(3);

scope.removeEmptyDetails = function(details){
            _.remove(details, function(detail){
                return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
            });
        };

@阿尔尼塔克

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

编辑:这个问题几乎在九年前就得到了回答,当时Array.prototype中没有太多有用的内置方法。

现在,当然,我建议您使用过滤方法。

请记住,此方法将返回一个新数组,其中包含传递给它的回调函数的条件的元素。

例如,如果要删除空值或未定义的值:

var array=[0,1,null,2,“”,3,undefined,3,,,,4,,,5,,6,,,];var filtered=array.filter(函数(el){返回el!=无效的});console.log(已过滤);

这取决于你认为什么是“空”的。例如,如果你处理字符串,上面的函数不会删除空字符串的元素。

我经常看到的一个典型模式是删除错误的元素,其中包括空字符串“”、0、NaN、null、undefined和false。

您可以传递给筛选方法、布尔构造函数或返回筛选条件函数中的相同元素,例如:

var filtered = array.filter(Boolean);

Or

var filtered = array.filter(function(el) { return el; });

在这两种情况下,这都是有效的,因为在第一种情况下过滤器方法将布尔构造函数作为函数调用,转换值,而在第二种情况下过滤方法在内部将回调的返回值隐式转换为布尔值。

如果您正在使用稀疏数组,并且正在尝试消除“空洞”,则可以使用filter方法传递返回true的回调,例如:

var spareArray=[0,,1,,,2,,3],cleanArray=sparseArray.filter(函数(){return true});console.log(cleanArray);//[ 0, 1, 2, 3 ]

老答案:不要这样做!

我使用这个方法,扩展了本机Array原型:

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

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

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

使用正则表达式筛选出无效条目

array = array.filter(/\w/);
filter + regexp