JS数组带有一个sort方法可以给数组排序,非常简单
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to sort the array.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
上面代码返回如下结果
Apple,Banana,Mango,Orange