Share via


Metodo sort

Restituisce un oggetto Array con gli elementi ordinati.

function sort(sortFunction : Function ) : Array

Argomenti

  • sortFunction
    Facoltativo. Nome della funzione utilizzata per determinare l'ordine degli elementi.

Note

Mediante il metodo sort viene eseguito l'ordinamento dell'oggetto Array esistente. Non viene quindi creato un nuovo oggetto Array durante l'esecuzione del metodo.

Se per l'argomento sortFunction viene specificata una funzione, essa dovrà restituire uno dei seguenti valori:

  • Un valore negativo se il primo argomento passato è minore del secondo argomento.

  • Zero se i due argomenti sono equivalenti.

  • Un valore positivo se il primo argomento è maggiore del secondo.

Se l'argomento sortFunction viene omesso, agli elementi verrà applicato un ordinamento crescente in base ai caratteri ASCII.

Esempio

Nell'esempio seguente viene illustrato l'utilizzo del metodo sort.

function SortDemo()
{
    // Create an array.
    var a = new Array("4", "11", "2", "10", "3", "1");

    // Sort in ascending ASCII order.
    // The array will contain 1,10,11,2,3,4.
    a.sort();

    // Sort the array elements numerically.
    // Use a function that compares array elements.
    // The array will contain 1,2,3,4,10,11.
    a.sort(CompareForSort);
}

// This function is used by the sort method
// to sort array elements numerically.
// It accepts two string arguments that
// contain numbers.
function CompareForSort(param1, param2)
{
    var first = parseInt(param1);
    var second = parseInt(param2);

    if (first == second)
        return 0;
    if (first < second)
        return -1;
    else
        return 1; 
}

Requisiti

Versione 2

Si applica a:

Oggetto Array

Vedere anche

Altre risorse

Oggetti (Visual Studio - JScript)