简体   繁体   中英

javascript- how can i sort my array (numbers) increasingly

<script>
        function ordine(){
            var numeri=new Array();
            for(i=0; i<=5;i++){
            numeri[i]=prompt("inserisci un numero");
            }
            for(x=0; x<=5; x++){
                for(j=0; j<=5; j++){
                    if(numeri[j]>numeri[j++]){
                        tmp=numeri[j];
                        numeri[j]=numeri[j++];
                        numeri[j++]=tmp;
                    }

                }

            }
            document.write(numeri);
        }
    </script>

i wrote this code to sort the array increseangly but it doesnt work. someone can explain me why?

Use sort() function:

document.write(numeri.sort());

Entered in random order, you will get the output:

1,2,3,4,5,7

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

The problem is in the if statement

if(numeri[j]>numeri[j++]){
                    tmp=numeri[j];
                    numeri[j]=numeri[j++];
                    numeri[j++]=tmp;
                }

the j++ means that in the next line the value of j will be j+1 . So, everytime you're accessing numeri[j++] you are actually accessing a different value.

if(numeri[i]>numeri[j]){
    tmp=numeri[i];
    numeri[i]=numeri[j];
    numeri[j]=tmp;
}

should work just fine

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