'Inversione di una matrice 'Il reverse()metodo inverte gli elementi in una matrice. 'Puoi usarlo per ordinare una matrice in ordine decrescente: 'Esempio 'var fruits = ["Banana", "Orange", "Apple", "Mango"]; 'fruits.sort(); // First sort the elements of fruits 'fruits.reverse(); // Then reverse the order of the element https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_sort_reverse <!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort Reverse</h2> <p>The reverse() method reverses the elements in an array.</p> <p>By combining sort() and reverse() you can sort an array in descending order.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> // Create and display an array: var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { // First sort the array fruits.sort(); // Then reverse it: fruits.reverse(); document.getElementById("demo").innerHTML = fruits; } </script> </body> </html> 'Usa lo stesso trucco per ordinare una matrice decrescente: 'Esempio 'var points = [40, 100, 1, 5, 25, 10]; 'points.sort(function(a, b){return b - a}); ' ritorna 100,40,25,10,5,1 https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_sort3 <!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in descending order.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction() { points.sort(function(a, b){return b - a}); document.getElementById("demo").innerHTML = points; } </script> </body> </html> |