排序复杂的JavaScript数组

时间:2013-01-14 01:34:26

标签: javascript

  

可能重复:
  How to sort an array of javascript objects?

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

在我使用的原始ActionScript代码中:

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

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

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

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

我在JS Bin上的脚本:http://jsbin.com/ibitez/1/edit

<!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" />
<title>Untitled Document</title>
<script>
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;
}
</script>
</head>

<body>
<div id="divSolution"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

您必须provide a callback to the sort method

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

这里是小提琴:http://jsfiddle.net/g2CQG/