数组排序希望实现:
不论升序还是降序,怎样实现空值始终排在最后;
如下数组
let arr = [null,"a", "b", null, "d",undefined,""]
希望排列结果是:
// 升序
["a", "b", "d", "", null, null, undefined]
// 降序
["d", "b", "a", "", null, null, undefined]
实现方法:
onChangeOrder(list,order){
list.sort((a,b)=>{
if (a === b) {
return 0;
}else if (a == null || a === "") {
return 1;
}else if (b == null || b === "") {
return -1;
}else if (order==="ascending") {
// 升序
return a < b ? -1 : 1;
}else {
// 降序
return a < b ? 1 : -1;
}
})
}

这篇博客介绍了如何使用JavaScript实现数组排序,确保空值(null和undefined)总是在排序后位于最后,无论升序还是降序。示例代码展示了onChangeOrder函数,根据传入的排序顺序参数,正确地将空值放到末尾。
8028

被折叠的 条评论
为什么被折叠?



