为什么"不想回复"出现在"非洲"按字母顺序排列?

时间:2015-03-19 15:33:51

标签: javascript arrays sorting

这里有点奇怪:我在JavaScript中对这些字符串进行排序:

"African"
"French"
"Did not wish to reply"
"Spanish"
"Gujerati"
"Bengali"

为此,我正在使用这段代码,其中nonPriorityLanguages是包含字符串的var []

nonPriorityLanguages.sort(function (o1, o2) {
    return o1.description > o2.description;
});

对于我某些未知的原因,列表中的第一个是"不希望回复"。这并不尊重字母顺序,因为结果应该是:

    "African"
    "Bengali"
    "Did not wish to reply"
    "French"
    "Gujerati"
    "Spanish"

2 个答案:

答案 0 :(得分:5)

这是因为callback中的sort应返回小于,大于或等于零以确定哪个元素更大。您遇到的问题是因为您只返回0和1(truefalse)。

var myPersonnalSort = function (o1, o2) {
    if(o1.description > o2.description){
        return 1;
    }else if(o1.description < o2.description){
        return -1;
    }else{
        return 0;
    }
};
nonPriorityLanguages.sort(myPersonnalSort);
priorityLanguages.sort(myPersonnalSort);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

答案 1 :(得分:2)

您不需要任何特定的回调:

[
  "African",
  "French",
  "Spanish",
  "Did not wish to reply",
  "Gujerati",
  "Bengali"
].sort()

返回

[
  "African",
  "Bengali",
  "Did not wish to reply",
  "French",
  "Gujerati",
  "Spanish"
]