排序复杂的JavaScript数组

Sort Complex JavaScript Array

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How to sort an array of javascript objects?

我正在尝试将一些旧的actionscript 2.0代码转换为javascript。一切正常,但我无法按分数对数组进行数字排序。

在我最初使用的actionscript代码中:

1
2
// Sort the capitals array so that the capitals with the lowest score will be at the top
capitalsList.sortOn("score", Array.NUMERIC);

这很好,但在JavaScript中不起作用。我把它改成:

1
capitalsList.sort("score", Array.NUMERIC);

但是阿拉巴马州仍然输出(康涅狄格州应该输出,因为它的分数是-1)。我错过了什么?

我在js bin上的脚本:http://jsbin.com/ibitez/1/edit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
Untitled Document

window.onload = function() {

    function capitalsConstructor(capitalName, stateName, score) {
        this.capitalName = capitalName;
        this.stateName = stateName;
        this.score = score;
    }

    // Create state capitals array
    var capitalsList = new Array();

    // All 50 capitals are loaded into the array with a score of 0
    // Sample limited to 10 capitals
    capitalsList[0] = new capitalsConstructor("Montgomery","Alabama", 0);
    capitalsList[1] = new capitalsConstructor("Juneau","Alaska", 0);
    capitalsList[2] = new capitalsConstructor("Phoenix","Arizona", 0);
    capitalsList[3] = new capitalsConstructor("Little Rock","Arkansas", 0);
    capitalsList[4] = new capitalsConstructor("Sacramento","California", 0);
    capitalsList[5] = new capitalsConstructor("Denver","Colorado", 0);
    capitalsList[6] = new capitalsConstructor("Hartford","Connecticut", -1);
    capitalsList[7] = new capitalsConstructor("Dover","Delaware", 0);
    capitalsList[8] = new capitalsConstructor("Tallahassee","Florida", 0);
    capitalsList[9] = new capitalsConstructor("Atlanta","Georgia", 0);

    capitalsList.sort("score", Array.NUMERIC);

    solution = capitalsList[0].stateName;

    document.getElementById("divSolution").innerText = solution;
}

</head>

<body>

</body>
</html>

您必须提供对sort方法的回调:

1
2
3
capitalsList = capitalsList.sort(function (a, b) {
    return a.score - b.score;
});

这是小提琴:http://jsfiddle.net/g2cqg/