Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    problema con la funzione sort

    Ciao a tutti, ho un problema con questo script: riassumo brevemente, devo ordinare dei numeri in un array presi da tastiera. Solo che a volte li ordina ed a volte no, ad esempio se inserisco 1,23,43,56,9 il 9 dovrebbe darmelo dopo l'uno invece non accade. Posto il codice

    <html>
    <head>

    <script type="text/javascript">
    var ordine = new Array(5);
    var y=0;
    for (y=0; y<5; y++)
    {
    ordine[y]=prompt('Inserisci un numero',' ');
    }
    ordine.sort();
    document.write(ordine);

    </script>
    </head>
    </html>

  2. #2
    Prova cosi':

    codice:
    <html>
    <head>
    
    <script type="text/javascript">
    var ordine = new Array(5); 
    var y=0; 
    for (y=0; y<5; y++) 
    { 
    ordine[y]=prompt('Inserisci un numero',' '); 
    }
    ordine.sort(function(a,b){return a - b});
    document.write(ordine);
    
    </script>
    </head>
    </html>
    Reference: http://www.w3schools.com/jsref/jsref_sort.asp

    Note: By default, the sort() method sorts the elements alphabetically and ascending. However, numbers will not be sorted correctly (40 comes before 5). To sort numbers, you must add a function that compare numbers.
    max

    Silence is better than bullshit.
    @mmarcon
    jHERE, Maps made easy

  3. #3
    Ok grazie funziona =)

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.