JavaScript TypedArray sort() 方法
JavaScript sort() 方法用于对数组进行排序,并返回排序后的数组。数组可以是任意类型,比如字符串、数字和字符。
语法
Array.sort()
参数
无参数。
返回值
排序后的数组。
浏览器支持
Chrome | Yes |
---|---|
Safari | Yes |
Firefox | Yes |
Opera | Yes |
示例1
JavaScript TypedArray sort() 方法。
<script>
// JavaScript to illustrate sort() method
function JavaTpoint() {
//Original string
var arr = [2, 5, 8, 1, 4]
//Sorting the array
document.write(arr.sort());
document.write("<br>");
document.write(arr);
// expected output: arr[Output:1,2,4,5,8]
}
JavaTpoint();
</script>
输出:
1,2,4,5,8
示例2
JavaScript TypedArray sort()方法。
<script>
// JavaScript to illustrate sort() method
function JavaTpoint() {
// Original array
var arr = [2, 5, 8, 1, 4];
document.write(arr.sort(function(a, b) {
return a=b;
}));
document.write("<br>");
document.write(arr);
// expected output: arr[Output:4,1,8,5,2]
}
JavaTpoint();
</script>
输出:
4,1,8,5,2
示例3
JavaScript TypedArray sort()方法。
<script>
// JavaScript to illustrate sort() method
function JavaTpoint() {
// Original array
var arr = [2, 5, 8, 1, 4];
document.write(arr.sort(function(a, b) {
return a<b;
}));
document.write("<br>");
document.write(arr);
// expected output: arr[Output:8,5,4,2,1]
}
JavaTpoint();
</script>
输出:
8,5,4,2,1
示例4
JavaScript TypedArray sort() 方法。
<script>
// JavaScript to illustrate sort() method
function JavaTpoint() {
// Original array
var arr = [2, 5, 8, 1, 4];
document.write(arr.sort(function(a, b) {
return a>b;
}));subarray
document.write("<br>");
document.write(arr);
// expected output: arr[Output:1,2,4,5,8]
}
JavaTpoint();
</script>
输出:
1,2,4,5,8