笑故挽风 2008-11-11 15:48 采纳率: 100%
浏览 3376
已采纳

删除数组中的空元素

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?

转载于:https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript

  • 写回答

30条回答 默认 最新

  • 谁还没个明天 2008-11-11 16:12
    关注

    EDIT: This question was answered almost 9 year ago, when there were not much useful built-in methods in the Array.prototype.

    Now, certainly I would just recommend you to use the filter method.

    Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it, for example, if you want to remove null or undefined values:

    var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
    
    var filtered = array.filter(function (el) {
      return el != null;
    });
    
    console.log(filtered);

    It will depend on what you consider to be "empty", for example if you were dealing with strings, the above function wouldn't remove elements that are an empty string.

    One common pattern that I see often used is to remove elements that are falsy, which include an empty string "", 0, NaN, null, undefined, and false.

    You can simply pass to the filter method, the Boolean constructor function, or simply return the same element in the filter criteria function, for example:

    var filtered = array.filter(Boolean);
    

    Or

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

    In both ways this works because the filter method in the first case, calls the Boolean constructor as a function, converting the value, and in the second case, the filter method internally converts the return value of the callback implicitly to Boolean.

    If you are working with sparse arrays, and you are trying to get rid of the "holes", you can simply use the filter method passing a callback that returns true, for example:

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

    Old answer: Don't do this!

    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,,,,]);
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号