1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>javascript数组去重算法-----3</title> 6 </head> 7 <body> 8 <script> 9 var arrDemo = new Array(); 10 11 arrDemo[0] = 10; 12 arrDemo[1] = 50; 13 arrDemo[2] = 51; 14 arrDemo[3] = 100; 15 16 arrDemo.sort(); //调用sort方法后,数组本身会被改变,即影响原数组 17 18 console.log(arrDemo);//10,100,50,51 默认情况下sort方法是按ascii字母顺序排序的,而非我们认为是按数字大小排序 19 20 arrDemo.sort(function(a,b){return a>b?1:-1});//从小到大排序 21 22 console.log(arrDemo);//10,50,51,100 23 24 arrDemo.sort(function(a,b){return a<b?1:-1});//从大到小排序 25 26 console.log(arrDemo); 27 </script> 28 </body> 29 </html>
时间: 2024-10-26 15:56:06