下面是一个例子 数组排序() 方法
null
- 项目1:
<script>
// JavaScript to illustrate sort() function
function
func() {
// Original string
var
arr = [
"Geeks"
,
"for"
,
"Geeks"
]
document.write(arr);
document.write(
"<br>"
);
// Sorting the array
document.write(arr.sort());
}
func();
</script>
- 输出:
Geeks,for,Geeks Geeks,Geeks,for
这个 arr.sort() 方法用于根据 比较 作用如果省略了该方法,则数组按顺序排序 升序 . 语法:
arr.sort(compareFunction)
参数: 此方法接受一个参数,如上所述,如下所述:
- 比较功能: 此参数用于根据不同属性和顺序对元素进行排序。
- 比较函数(a,b)<0
然后答案中a排在b之前。
- 比较函数(a,b)>0
然后答案中b在a之前。
- 比较函数(a,b)=0
然后a和b的顺序保持不变。
- 比较函数(a,b)<0
返回值: 此方法返回排序后的原始数组的引用。
下面的示例演示了JavaScript数组sort()方法:
var arr = [2, 5, 8, 1, 4] document.write(arr.sort()); document.write(arr);
输出:
1,2,4,5,8 1,2,4,5,8
var arr = [2, 5, 8, 1, 4] document.write(arr.sort(function(a, b) { return a + 2 * b; })); document.write(arr);
输出:
2,5,8,1,4 2,5,8,1,4
下面提供了上述方法的代码: 项目1:
<script> // JavaScript to illustrate sort() function function func() { //Original string var arr = [2, 5, 8, 1, 4] //Sorting the array document.write(arr.sort()); document.write( "<br>" ); document.write(arr); } func(); </script> |
输出:
1,2,4,5,8 1,2,4,5,8
项目2:
<script> // JavaScript to illustrate sort() function function func() { // Original array var arr = [2, 5, 8, 1, 4]; document.write(arr.sort( function (a, b) { return a + 2 * b; })); document.write( "<br>" ); document.write(arr); } func(); </script> |
输出:
4,1,8,5,2 4,1,8,5,2
支持的浏览器: JavaScript数组sort()方法支持的浏览器如下所示:
- 谷歌Chrome 1及以上版本
- 边缘12及以上
- Firefox 1及以上版本
- Internet Explorer 5.5及以上版本
- 歌剧4及以上
- Safari 1及以上
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END