数组排序,空值排在最后 sort()/reverse()

//按sort由小到大排序 空值排在最后
let formJson =[1,3,5,6, "", 10, null]
formJson = formJson.sort(function(a, b) {
   return (b!= '' && b!= null) - (a!= '' && a!= null) || a- b;
});
console.info(formJson);// [1, 3, 5, 6, 10, "", null]
//从小到大排序
[1,3,4,0,7,10].sort(function(a,b){return a>b?1:-1});
//[0, 1, 3, 4, 7, 10]

//从大到小排序
[0,10,4,5,7,12,3].sort(function(a,b){return a<b?1:-1});
//[12, 10, 7, 5, 4, 3, 0]

//有空值时由大到小排序,空值排在最后
[1,3,4,0,7,10, '',null].sort(function(a,b){return a>b?1:-1}).reverse();
// [10, 7, 4, 3, 1, 0, "", null]

猜你喜欢

转载自blog.csdn.net/Sunny_lxm/article/details/109643602