sort()方法排序
var arr = ["G","A","C","B","I","H","G","I","B"]; arr.sort(); console.log(arr);
注意:sort函数默认是按照字符顺序排的,隐式将数字转为string(//比字符编码顺序)
var arr = [23,435,456,23,2,345,2,32,11,324,32,43,65,667,78,43]; arr.sort(); console.log(arr);
var arr = [23,435,456,23,2,345,2,32,11,324,32,43,65,667,78,43]; // 升序 arr.sort(function(a,b){ //如果a要放在b前面,那么返回负数 //如果a要放在b后面,那么返回正数 //如果a和b不区分大小,那么返回0 if(a < b){ return -1; //满足第一个条件,返回值是-1,a要排在b前面 }else if(a > b){ return 1; //满足第二个条件,返回值是1,a要排在b后面 }else if(a == b){ return 0; } }); console.log(arr);
//按五角星的个数排序 var arr = ["★★★","★★★★★","★★","★★★","★","★★★★★★★★","★★★","★★★★★"]; arr.sort(function(a,b){ if(a.length > b.length){ return -1; //满足第一个条件,返回值是-1,a要排在b前面 }else if(a.length < b.length){ return 1; //满足第二个条件,返回值是1,a要排在b后面 }else{ return 0; } }); console.log(arr);