jQuery 如何使用jquery从数组中删除空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12745800/
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 11:58:49  来源:igfitidea点击:

how to remove null values from an array using jquery

jqueryarrays

提问by Kumaran

Possible Duplicate:
Remove empty elements from an array in Javascript

可能的重复:
从 Javascript 中的数组中删除空元素

I want to remove nullor empty elements from an array using jquery

我想null使用从数组中删除或清空元素jquery

var clientName= new Array();
clientName[0] = "Hyman";
clientName[1] = "";
clientName[2] = "john";
clientName[2] = "peter";

Please give some suggestions.

请给出一些建议。

回答by Hans Hohenfeld

Use the jquery grepfunction, it'll identify array elements that pass criteria you define

使用 jquery grep函数,它将识别通过您定义的条件的数组元素

arr = jQuery.grep(arr, function(n, i){
  return (n !== "" && n != null);
});

回答by VisioN

There is no need in jQuery, use plain JavaScript (it is faster!):

在 jQuery 中不需要,使用纯 JavaScript(它更快!):

var newArray = [];
for (var i = 0; i < clientname.length; i++) {
    if (clientname[i] !== "" && clientname[i] !== null) {
        newArray.push(clientname[i]);
    }
}
console.log(newArray);

Another simple solution for modern browsers (using Array filter()method):

现代浏览器的另一个简单解决方案(使用 Arrayfilter()方法):

clientname.filter(function(value) {
    return value !== "" && value !== null;
});

回答by Richard Neil Ilagan

Was thinking that since jQuery's .map()function relies on returning something notnull / undefined, you can get away with just something like this:

认为由于 jQuery 的.map()函数依赖于返回空/未定义的东西,你可以摆脱这样的事情:

var new_array = $.map(old_array, function (el) {
    return el !== '' ? el : null;
});

You still have to check for the empty string, but you really don't have to check for the null and undefined anymore, so that's one less complication in your logic.

您仍然需要检查空字符串,但您确实不必再检查 null 和 undefined 了,这样您的逻辑就少了一个复杂性。

回答by Richard Neil Ilagan

  1. Create a new empty array.
  2. Go into a foreach loop and add items to new array if value is not equal to ''.
  1. 创建一个新的空数组。
  2. 如果 value 不等于 '',则进入 foreach 循环并将项目添加到新数组。

回答by Laurent Brieu

Try this :

尝试这个 :

$.each(clientname, function(key, value) { 
  if (value === 'undefined' || value === '')
     clientname.splice(key,1);
});

回答by XMen

Use the following code:

使用以下代码:

var newarr=[];
for(var i=0; i<len(clientname);i++){

   if(clientname[i] !== "" && clientname[i] !== null){
    newarr.push(clientname[i]);
   }
}