简体   繁体   中英

For loop stuck in an infinite loop

My for loop is stuck in an infinite loop and I can't figure out why. Can someone tell me what I am doing wrong here?

jData is an array extracted from a text file. The images are currently stored in a comma separated string and this loop should extract them and display them one by one.

  for( var i = 0 ; i < jData.length ; i++ ){ //runs loop to populate container. //console.log("array images contains " + jData[i].imgs); if (jData[i].imgs){ var sImages = jData[i].imgs; var aImages = sImages.split(','); for( var i = 0 ; i < aImages.length; i++) { sPropertyTemplate = sPropertyTemplate.replace( "{{images"+i+"}}" , aImages[i] ); console.log(aImages[i]); break; } } var sPropertyTemplate = sProperty; sPropertyTemplate = sPropertyTemplate.replace( "{{id}}" , jData[i].sUniqueId ); sPropertyTemplate = sPropertyTemplate.replace( "{{address}}" , jData[i].sAddress ); sPropertyTemplate = sPropertyTemplate.replace( "{{type}}" , jData[i].sType ); sPropertyTemplate = sPropertyTemplate.replace( "{{price}}" , jData[i].iPrice ); sPropertyTemplate = sPropertyTemplate.replace( "{{locLat}}" , jData[i].lat ); sPropertyTemplate = sPropertyTemplate.replace( "{{LocLng}}" , jData[i].lng ); 

You are using the same variable i in both, the inner and outer loop. So you will always overwrite its value it should have in the outer for-loop.

What you should do, use a different variable for the inner loop, such as j :

for( var j = 0 ; j < aImages.length; j++) {
    sPropertyTemplate = sPropertyTemplate.replace( "{{images"+j+"}}" , aImages[j] );
    console.log(aImages[j]);
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM