从字符串数组中删除一个空字符串 - 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
remove an empty string from array of strings - JQuery
提问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 filter
anywhere 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
回答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];