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

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


当前回答

实际上,您可以使用ES6+方法,假设数组如下:

const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];

答案可以是以下两种方式之一:

第一种方式:常量clearArray=arr.filter(i=>i);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]第二种方式:const clearArray=arr.filter(布尔值);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

2022年10月14日更新:

这两个答案并不完全正确,即使在给定的例子中,是的,它是有效的,但请注意给定数组中的数字0,通过这两种方式,数字0都会消失,这显然与使用布尔强制检查项目有关。

完全正确的方法是检查nulish并删除它们:

const notNil = (i) => !(typeof i === 'undefined' || i === null);

const clearArray = arr.filter(i => isNil(i));

常量arr=[1,2,3,未定义,4,5,6,未定义、7,8,未定义;未定义,0,9];常量notNil=(i)=>!(类型i===“未定义”||i===null);console.log(“非nil:”,arr.filter(非nil));

其他回答

这可能会帮助您: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));
            });
        };

这是另一种方法:

var arr = ["a", "b", undefined, undefined, "e", undefined, "g", undefined, "i", "", "k"]
var cleanArr = arr.join('.').split(/\.+/);

删除空元素的最佳方法是使用Array.prototype.filter(),正如其他答案中已经提到的那样。

不幸的是,IE<9不支持Array.prototype.filter()。如果您仍然需要支持IE8或更旧版本的IE,可以使用以下polyfill在这些浏览器中添加对Array.protocol.filter()的支持:

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';
    if (this === void 0 || this === null) {
      throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }
    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }
    return res;
  };
}

试试这个。将数组传递给它,它将返回并删除空元素*更新以解决Jason指出的错误

function removeEmptyElem(ary) {
    for (var i = ary.length - 1; i >= 0; i--) {
        if (ary[i] == undefined)  {
            ary.splice(i, 1);
        }       
    }
    return ary;
}

只需使用array.filter(字符串);它返回javascript中数组的所有非空元素