[js] sort
排序 sort()
最好在sort()使用使用函数判断,不然遇到相同值时,排序会出错
var numbers = [5, 4, 3, 2, 1]; numbers.sort(function(a, b) { console.log(a + ':' + b); return a - b; }); //numbers.sort((a, b) => a - b);//从小到大 console.log(numbers); numbers.sort(function(a, b) { console.log(a + ':' + b); return b - a; }); //numbers.sort((a, b) => b - a);//从大到小 console.log(numbers); //本质好像是快速排序 //字母数字混杂排序,从 数字从小到大-A-Z-a-z的顺序排列,大写顺序高于小写 var letter = ['e', 'd', 'c', 'b', 'a']; letter.sort(); console.log(letter); var letter = ['a', 'b', 'd', 'c', 'e']; letter.sort(); console.log(letter); var letter = ['a', 'b', 'D', 'C', 'E',1,2]; letter.sort(); console.log(letter); var letter = ['E', 'C', 'D', 'b', 'a','2','1']; letter.sort(); console.log(letter);