简体   繁体   中英

Why does this javascript code have an infinite loop?

optionElements is a 2d array. Each element has an array of length 2. These are an integer number and an element. I have a select list called linkbox, and i want to add all of the elements to the select list. The order I want them to go in is important, and is determined by the number each element has. It should be smallest to highest. So think of it like this:

optionElements is:

[ [5, <option>], [3, <option], [4, <option], [1, <option], [2, <option]]

and it would add them to link box in order of those numbers. BUT that is not what happens. It is an infinite loop after the first time. I added the x constraint just to stop it from freezing my browser but you can ignore it.

var b;
var smallest;
var samllestIndex;
var x = 0;
while(optionElements.length > 0 && ++x < 100)
{
    smallestIndex = 0;
    smallest = optionElements[0][0];
    b = 0;
    while( ++b < optionElements.length)
    {
        if(optionElements[b][0] > smallest)
        {
            smallestIndex = b;
            smallest = optionElements[b][0];
        }                    
    }                    
    linkbox.appendChild(optionElements[smallestIndex][1]);
    optionElements.unshift(optionElements[smallestIndex]);
}

can someone point out to me where my problem is?

Update

forgot to add the > sign is wrong in the while loop but is not the cause of the problem.

It's an infinite loop because unshift adds the array you're passing in to the one you're calling it on. So the outer loop checks if optionElements has more items than 0, then at the end it gets larger, so that loop never exits. http://www.w3schools.com/jsref/jsref_unshift.asp

I'm also not sure why you're doing it this way in any case. Why not just sort the optionElements array first, then iterate over it once to add each element to the linkbox?

from javascript unshift() function :

The unshift() method adds new elements to the beginning of an array, and returns the new length.

This means you keep adding elements to the beginning instead of removing them, giving your infinite loop.

Try using a counter to run the loop optionElements.length timesbetter performance). Or you can use shift() to get the desired effect:

optionElements.shift();

:D

I can tell you that .unshift() doesn't work in IE. So you might want to test in Mozilla/Safari if you were using IE before.

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