本文介绍了字典的Javascript排序数组,按字母顺序排列,可能有null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了一个问题.我正在按联系人的名字对联系人进行排序,但是有时我碰到缺少名字的联系人.有谁知道如何更改此方法以使其起作用?谢谢
I am running into an issue. I am sorting contacts by their first name but sometimes I run into a contact that is missing the first name. Does anyone know how to change this method to make it work? Thanks
这是我正在使用的排序方法.
This is the sorting method I am using.
function sortAZ(ob1,ob2) {
var n1 = ob1.firstName.toLowerCase()
var n2 = ob2.firstName.toLowerCase()
if (n1 > n2) {return 1}
else if (n1 < n2){return -1}
else { return 0}//nothing to split
};
data.sort(sortAZ);
推荐答案
function sortAZ(ob1,ob2) {
// Handles case they're both equal (or both missing)
if (obj1 == obj2) {return 0}
// Handle case one is missing
if (obj2 == null|| obj2 == "") {return 1}
if (obj1 == null|| obj1 == "") {return -1}
var n1 = ob1.firstName.toLowerCase()
var n2 = ob2.firstName.toLowerCase()
if (n1 > n2) {return 1}
else if (n1 < n2){return -1}
else { return 0}//nothing to split
};
这篇关于字典的Javascript排序数组,按字母顺序排列,可能有null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!