0

I have an array with the structure

var citizens1 = [{lat:null,lng:null,socialSecurityNumber:null}];

I would like to use a loop to print the values of each element however this does not work for me:

Code

function animate(index,d) {  

       if (d>eol[index]) {

        marker[index].setPosition(endLocation[index].latlng);       

        if(marker[index].getPosition() == endLocation[index].latlng){
            console.log('Completed'+' '+index);
        }  


        return;
     }

         var p = polyline[index].GetPointAtDistance(d);
         marker[index].setPosition(p);
         updatePoly(index,d);

         timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);

         citizens1.push({lat:marker[index].getPosition().lat(),lng:marker[index].getPosition().lng(),socialSecurityNumber:global_citizens[index].socialSecurityNumber});

         if(citizens1.length = '500'){           
             console.log('500 records saved');          
             window.clearTimeout( timerHandle);

             for(var i = 0; i < citizens1.length ; i++){


                 console.log(citizens1.lat +',' +citizens1.lng+','+citizens1.socialSecurityNumber); 




             }

             citizens1 = [];
         }

  }

Error

TypeError: citizens1[i].lat is undefined 
5
  • 2
    Is the period after name a typo just in here, or in your real program as well? Commented Oct 14, 2013 at 2:44
  • sorry that was a typo will fix this Commented Oct 14, 2013 at 2:44
  • 1
    Could you show your full code, or is this it? Commented Oct 14, 2013 at 2:45
  • 1
    it seems to work, jsfiddle.net/KKAg5 Commented Oct 14, 2013 at 2:47
  • 2
    If this code doesn't work, then it's because you array doesn't contain what you think it does. I'd suggest you do a console.log(Students[i]) instead and see what's really there. Commented Oct 14, 2013 at 2:48

3 Answers 3

1

citizens1.length = '500' should be citizens1.length == 500

Also

console.log(citizens1.lat +',' +citizens1.lng+','+citizens1.socialSecurityNumber); 

should be

console.log(citizens1[i].lat +',' +citizens1[i].lng+','+citizens1[i].socialSecurityNumber); 

You need to print the properties of each element of the array, not of the array itself.

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

1 Comment

i will fix that thank you however it still doesn't fix the printing of each element
1

This line:

console.log(citizens1.lat +',' +citizens1.lng+','+citizens1.socialSecurityNumber); 

needs to have the array index in it:

console.log(citizens1[i].lat +',' +citizens1[i].lng+','+citizens1[i].socialSecurityNumber); 

Comments

1

I hope you have initialised the Students as

Students = [{name:null,age:null,address:null}];

1 Comment

i modified the code posting the real code instead of an example of my scenario

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.