javascript数组排序-----1

时间:2023-12-14 15:05:38
 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript数组去重算法-----3</title>
</head>
<body>
<script>
var arrDemo = new Array(); arrDemo[0] = 10;
arrDemo[1] = 50;
arrDemo[2] = 51;
arrDemo[3] = 100; arrDemo.sort(); //调用sort方法后,数组本身会被改变,即影响原数组 console.log(arrDemo);//10,100,50,51 默认情况下sort方法是按ascii字母顺序排序的,而非我们认为是按数字大小排序 arrDemo.sort(function(a,b){return a>b?1:-1});//从小到大排序 console.log(arrDemo);//10,50,51,100 arrDemo.sort(function(a,b){return a<b?1:-1});//从大到小排序 console.log(arrDemo);
</script>
</body>
</html>