how to remove null values from an array using jquery

Possible Duplicate:
Remove empty elements from an array in Javascript

I want to remove null or empty elements from an array using jquery

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

Please give some suggestions.


使用jquery grep函数,它会标识传递您定义的标准的数组元素

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

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

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):

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

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

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.

链接地址: http://www.djcxy.com/p/37738.html

上一篇: 我怎样才能“重置”一个数组的键?

下一篇: 如何使用jquery从数组中删除空值