从在Javascript数组中删除空元素 [英] Remove empty elements from an array in Javascript

查看:135
本文介绍了从在Javascript数组中删除空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I remove empty elements from an array in JavaScript?

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

Is there a straightforward way, or do I need to loop through it and remove them manually?

推荐答案

我用这个方法,延长本机阵列原型:

I use this method, extending the native Array prototype:

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

或者你可以简单地按现有的元素融入到其他数组:

Or you can simply push the existing elements into other array:

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

这篇关于从在Javascript数组中删除空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆