从字符串数组中删除一个空字符串 - JQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14453670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:35:05  来源:igfitidea点击:

remove an empty string from array of strings - JQuery

jqueryarrays

提问by Sadiksha Gautam

I have an array ["Lorem", "", "ipsum"]. I would like to remove the empty string from this array and get ["Lorem", "ipsum"].

我有一个数组["Lorem", "", "ipsum"]。我想从此数组中删除空字符串并获取["Lorem", "ipsum"].

Is there any way to do this without using the loop and traversing through each element and removing it?

有没有办法在不使用循环并遍历每个元素并删除它的情况下做到这一点?

回答by Denys Séguret

You may use filter:

您可以使用filter

var newArray = oldArray.filter(function(v){return v!==''});

The MDNhas a workaround for IE8 compatibility. You might also use a good old loop if you're not going to use filteranywhere else, there's no problem with looping...

MDN有一个解决 IE8 兼容性的方法。如果您不打算filter在其他任何地方使用,您也可以使用一个很好的旧循环,循环没有问题......

回答by venimus

If you use Javascript 1.6 (probably wont work on IE8 or less) you can use

如果您使用 Javascript 1.6(可能不适用于 IE8 或更低版本),您可以使用

arr.filter(Boolean) //filters all non-true values

arr.filter(Boolean) //filters all non-true values

eg.

例如。

[1, false, "", undefined, null, "Lorem"].filter(Boolean); // [1, "Lorem"]

[1, false, "", undefined, null, "Lorem"].filter(Boolean); // [1, "Lorem"]

回答by zkhr

Another alternative is to use the jquery's .map()function:

另一种选择是使用 jquery 的.map()函数:

var newArray = $.map( oldArray, function(v){
  return v === "" ? null : v;
});

回答by Dipesh Parmar

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

function cleanArray(actual)
{
    var newArray = new Array();
    for(var i = 0; i<actual.length; i++)
    {
        if (actual[i])
        {
            newArray.push(actual[i]);
        }
    }
    return newArray;
}

$(function()
{
    var old = ["Lorem", "", "ipsum"];

    var newArr = cleanArray(old);

    console.log(newArr)
});
</script>

Without Loop

无循环

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

$(function()
{
    var arr = ["Lorem", "", "ipsum"];

    arr = $.grep(arr,function(n){
        return(n);
    });

    console.log(arr)
});
</script>

Both is tested.

两者都经过测试。

回答by sansid1983

var arr = [ a, b, c, , e, f, , g, h ];

var arr = [ a, b, c, , e, f, , g, h];

arr = jQuery.grep(arr, function(n){ return (n); });

arr = jQuery.grep(arr, function(n){ return (n); });

arr is now [ a, b, c, d, e, f, g];

arr 现在是 [ a, b, c, d, e, f, g];