array.sort()是JavaScript中的內置方法,用於對數組進行排序。數組可以是任何類型,例如字符串,數字,字符等。語法:
array.sort()
在這裏,數組是將要排序的一組值。
參數:它不接受任何參數。
返回值:它不返回任何東西。
例子:
Input: var arr = ["Manish", "Rishabh", "Nitika", "Harshita"]; Output: Harshita, Manish, Nitika, Rishabh Input: var arr = [1, 4, 3, 2]; Output: 1, 2, 3, 4
代碼1:要對字符串數組進行排序:
<html>
<body>
<p>Click on the Sort button to sort the array</p>
<!-- button for click event -->
<!-- onclick event is generated when the button is clicked -->
<p id="demo"></p>
<script>
<!-- array of names -->
var names = [" Manish", " Rishabh", " Nitika", " Harshita"];
document.getElementById("demo").innerHTML = names;
<!-- sortAlphabet function that sort above array alphabetically -->
function sortAlphabet() {
names.sort();
document.getElementById("demo").innerHTML = names;
}
</script>
<button onclick="sortAlphabet()"> Sort </button>
</body>
</html>
輸出:
在單擊“sort”按鈕之前,
單擊“sort”按鈕後,
代碼2:要對整數數組進行排序:
<html>
<body>
<p>Click on the Sort button to sort the array</p>
<!-- button for click event -->
<!-- onclick event is generated when the button is clicked-->
<p id="demo"></p>
<script>
<!-- array numbers -->
var numbers = [7, 1, 6, 9, 2];
document.getElementById("demo").innerHTML = numbers;
<!-- sortNumber function that sort the array -->
function sortNumber() {
numbers.sort();
document.getElementById("demo").innerHTML = numbers;
}
</script>
<button onclick="sortNumber()"> Sort </button>
</body>
</html>
輸出:
在單擊“sort”按鈕之前,
單擊“sort”按鈕後,
相關用法
- Javascript Array sort()用法及代碼示例
- Javascript typedArray.sort()用法及代碼示例
- Javascript Replace()用法及代碼示例
- Javascript exec()用法及代碼示例
- Javascript padStart()用法及代碼示例
- Javascript Uint32Array from()用法及代碼示例
- Javascript Array.from()用法及代碼示例
注:本文由純淨天空篩選整理自Naman_Garg大神的英文原創作品 JavaScript | Sort() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。