Why does this javascript code have an infinite loop?

optionElements is a 2d array. Each element has an array of length 2. This is an integer and an element. I have a select list called linkbox and I want to add all the items to the select list. The order in which I want them to enter is important and is determined by the number that each element has. It should be the smallest to the highest. So think of it this way:

optionElements:

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

and this will add them to the link field in the order of these numbers. BUT this is not what happens. This is an endless loop after the first time. I added an x ​​constraint 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 me where is my problem?

Update

I forgot to add the> sign in the while field, but it is not the cause of the problem.

+3
3

, unshift , , , . , , Elements , 0, , . http://www.w3schools.com/jsref/jsref_unshift.asp

, . optionsElements, , ?

+4

from javascript unshift():

unshift() .

, , , .

optionElements.length ). shift(), :

optionElements.shift();

: D

+2

I can tell you that .unshift () does not work in IE. This way you can test Mozilla / Safari if you used IE before.

+1
source

Source: https://habr.com/ru/post/1745347/


All Articles