Why does this javascript code have an infinite loop?
- by asdas
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?