Why does this javascript code have an infinite loop?
Posted
by asdas
on Stack Overflow
See other posts from Stack Overflow
or by asdas
Published on 2010-05-13T20:22:45Z
Indexed on
2010/05/13
20:34 UTC
Read the original article
Hit count: 193
JavaScript
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?
© Stack Overflow or respective owner