JavaScript 中的 Array.prototype.sort()。
JavaScript Array.prototype.sort() 方法用于对数组排序。排序顺序可以是字母顺序、数字顺序、升序或降序。
以下是 Array.prototype.sort() 方法的代码 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample,.result { font-size: 18px; font-weight: 500; color: red; } .result { color: rebeccapurple; } </style> </head> <body> <h1>JavaScript Array.prototype.sort() method</h1> <div class="sample"></div> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to sort the array above</h3> <script> let sampleEle = document.querySelector(".sample"); let resultEle = document.querySelector(".result"); let arr = [9, 1, 4, 2, 99, 11, 22]; sampleEle.innerHTML = "Unsorted array = " + arr; document.querySelector(".Btn").addEventListener("click", () => { resultEle.innerHTML = "Sorted array = " + arr.sort(); }); </script> </body> </html>
输出
以上代码将生成以下输出 −
单击“点击这里”按钮时 −
广告