Reputation: 465
I have this code:
var arrayInstSaude = new Array();
$("input[name='uniSaudePrj']:checked").each(function(){
arrayInstSaude[$(this).val()]=$(this).val();
});
For some reason it gives me a messed array. Exemple:
If I do that for 5 elements:
for (var i = 1; i <=arrayInstSaude.length; i++) {
alert(arrayInstSaude[i]);
}
I will have 1,2,undefined,undefined,5,6,7,undefined, while it was expected to have 1,2,5,6,7. Someone know what is going on? Thanks!
Upvotes: 0
Views: 54
Reputation: 465
I think this code is enough for my propouse:
var arrayInstSaude = new Array();
var k=0;
$("input[name='uniSaudePrj']:checked").each(function(){
arrayInstSaude[k]=$(this).val();
k++;
});
It was important to observe that the length is the highest index plus one. So, to retrieve the elements we could use
for(k=0;k<arrayInstSaude.length;k++){
alert(arrayInstSaude[k]);
}
Because we know that the last element is allways empty.
Upvotes: 0
Reputation: 25834
Replace
for (var i = 1; i <=arrayInstSaude.length; i++) {
alert(arrayInstSaude[i]);
}
with
for (var i in arrayInstSaude) {
alert(arrayInstSaude[i]);
}
Consider reading this discussion by olliej.
Upvotes: 0
Reputation: 887453
Arrays are always contiguous.
The length is simply the highest index plus one.
It sounds like you want a regular object that happens to have numeric keys (and no length).
Upvotes: 3