0

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 check 1 element value eq 1. It gives me the arrayInstSaude length equal 2.
  • if I check 2 elements value eq 2. It gives me the arrayInstSaude length equal 3.
  • if I check 3 elements value eq 5. It gives me the arrayInstSaude length equal 6.
  • if I check 4 elements value eq 6. It gives me the arrayInstSaude length equal 7.
  • if I check 5 elements value eq 7. It gives me the arrayInstSaude length equal 8.

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!

2
  • 2
    Array indexes start from 0. If you create array[1], the length is 2 because it has array[0] and array[1]. Commented Nov 4, 2013 at 17:14
  • 1
    When you create arrayInstSaude[5] it automatically creates 3 & 4, but with no values. It can't just leave them out. Commented Nov 4, 2013 at 17:17

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.