简体   繁体   中英

Javascript: Iterating over an array causes an infinite loop?

I'm trying to iterate over some data in Javascript, using the following code:

for (var i = 0; i < fromdata.length; i++) {
    var mainid = fromdata[i].id;
    var sub = afcHelper_Submissions[mainid];
    /* do more stuff */

fromdata is an array of Objects that looks something like this:

[{ type="ffu", to=" Jon Corzine ", id=1, more...}, { type="ffu", to=" Jon Corzine ", id=2, more...}]

As you can see, I just want to get each object's id and store it to mainid and then do some more with it; however, I run into trouble: looping! Looping! Looping! The loop keeps running again and again. It never stops, and just manages to freeze up Firebug.

Update : Here's the "do more stuff", in all its pastebin glory: http://pastebin.com/Mfr90uq7 . Note that I changed the variable name from sub to sub_m to avoid a potential conflict, but the problem persisted.

A loop only can be infinite if the condition is always true. In your case it looks that it should reach a false , but provably formData is getting new elements each iteration of the loop or i is being modified and returned to previous values.

What I recomend is to create variables that will be used only for comparasion purposes:

var max = fromdata.length;
for (var count = 0; count < max; count++) {
    var i = count;
    // your stuff using formdata and i

Now max and count will not be modified by the code in the loop and the loop will reach an end.

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