如何从数组中删除空数组值(“")? [英] How to remove empty array values ("") from an array?

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

问题描述

我有一个二维数组,用 jQuery 从 html 表生成,但有些值为空,所以显示 "".

I have an two dimensional array, generated from a html table with jQuery, but some values are empty so "" is displayed.

如何删除空值?

  <table>    
    <tr>
      <th>1A</th>
      <th>1B</th>
      <th>1C</th>
    </tr>
    <tr>
      <td>2A</td>
      <td>2B</td>
      <td>2C</td>
    </tr>
    <tr>
      <td></td>
      <td>3B</td>
      <td>3C</td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td>4C</td>
    </tr>
  </table>
<script>
    var columns = $('tr').first().children().map(function(i) {
        return [
            $('tr').map(function(){
                return $(this).children().eq(i).text()
            }).get()
        ]
    }).get();
<script>

我已经尝试过以下代码:

for( var i = 0; i < columns[0].length; i++){ 
   if ( columns[0][i] === "") {
    columns[0].splice(i, 1); 
   }
}

它适用于一些空值,但由于某种原因,并非所有值都被删除了.

It worked for some empty values, but not all of them got removed for some reason.

输出:https://imgur.com/e7BAdQK

推荐答案

您可以使用以下过滤器:

You could use the filter like:

arr = arr.filter(item => item);

示例:

let arr = ['One', 'Two', '', 'Four', '', ''];
arr = arr.filter(item => item);
console.log(arr);

// Result
// ['One', 'Two', 'Four']

因为空字符串的计算结果为布尔值 false.它适用于所有虚假值,如 0falsenullundefined''

Because an empty string evaluates to boolean false. It works with all falsy values like 0, false, null, undefined, '', etc.

演示

如果您想保留一些值,例如数字 0(零),您可以使用 item !== undefined.这仅过滤未定义的值.请记住修剪您的字符串或使用正则表达式检查以确保没有空格的空字符串.

If you want to keep some values like number 0 (zero) you could use item !== undefined. This filters only undefined values. Keep in mind to trim your string or check with regex to ensure empty strings without whitespaces.

这篇关于如何从数组中删除空数组值(“")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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