how to exclude blank values in jquery array?
there are following input fields with datepicker class:
<input type="text" class="datepicker" value="" />
<input type="text" class="datepicker" value="" />
<input type="text" class="datepicker" value="2011-02-15" />
<input type="text" class="datepicker" value="2011-02-16" />
I need to create an array of dates, exclude blank values and return maximum value. Following code doesn't seem to exclude blank values:
var datelist = [];
$(".date开发者_开发技巧picker").each(function(i) {
if (this.value!="") {datelist[i] = this.value;}
});
datelist.sort();
datelist.reverse();
alert(datelist); //,,2011-02-16,2011-02-15
alert(datelist[0]); //undefined
What's the catch?
It excludes the empty values. That is why datalist[0]
is undefined
.
The value with index 0
is empty, hence datelist[0] = this.value;
is not executed. The only values set in the array are the ones with keys 2
and 3
, making the keys 0
, 1
and all >3
undefined
.
If the values were included, you would not get undefined
but an empty string.
You should not use the index for adding values to the array. push()
them:
$(".datepicker").each(function(i) {
if (this.value!="") {datelist.push(this.value);}
});
That said, a more concise way would be:
var datelist = $('.datepicker[value!=""]').map(function() {
return this.value;
}).get();
Reference: .map()
, .get()
Try
$('.datepicker[value!=""]')
You can use the .map
and $.grep
methods to get the array and remove the empty items:
Get all values into an array:
var datelist = $(".datepicker").map(function() { return this.value; }).get();
Remove empty items from the array:
datelist = $.grep(datelist, function(s) { return s.length != 0; });
It's like doing a = []; a[0] = 1; a[2] = 3;
- if you skip an index it will be filled with an undefined
value. So you could change your code to something like this:
$(".datepicker").each(function() {
if (this.value != "" || this.value != undefined) {
datelist[datelist.length] = this.value;
}
});
First, do not use this
in each but the second function argument - see http://fixingthesejquery.com/#slide29
Then, append values to the list instead of using an index (remember, you do not create an array element for some values of i
!):
if (this.value) {
datelist.push(this.value);
}
So, the code should be like this:
var dateList = [];
$(".datepicker").each(function(i, elem) {
if (elem.value) {
dateList[i] = elem.value;
}
});
dateList.sort();
dateList.reverse();
Try changing this portion -
var datelist = [];
$(".datepicker").each(function(i) {
if (this.value!="") {datelist[i] = this.value;}
});
to this -
var datelist = [];
var index = 0;
$(".datepicker").each(function(i) {
if ( $(this).val() != "")
{
datelist[index++] = $(this).val();
}
});
精彩评论