0

我之前发布过关于在 javascript 中对对象进行排序的文章。对于无法对对象进行排序,我有一个很大的禁忌。

我被告知的路径是将对象转换为数组。

我已将 totalScore 声明为一个新数组,并对其应用降序函数。- 这不起作用。任何想法为什么?

这是代码(我正在开发一个井字游戏):

var data = {
        "arr0" : ["1","1","1","0","0","0","0","0","0"],
        "arr1" : ["1","0","0","0","1","0","0","0","1"],
        "arr2" : ["0","0","0","1","1","1","0","0","0"],
        "arr3" : ["0","0","0","0","0","0","1","1","1"],
        "arr4" : ["0","0","1","0","1","0","1","0","0"],
        "arr5" : ["1","0","0","1","0","0","1","0","0"],
        "arr6" : ["0","1","0","0","1","0","0","1","0"],
        "arr7" : ["0","0","1","0","0","1","0","0","1"]
    };

function win(){
        var pocket,
            totalScore = new Array,
            score,
            maxM,
            i;

        jQuery.each(data, function(d_key, d_val){
            score = 0;
            i = 0;
            jQuery.each(d_val, function(key, val){
                pocket = jQuery(document).find('[data-kcpos="'+key+'"]');
                if(val == 1 && jQuery(pocket).hasClass("blank")){
                    score += 1;
                } else if(val == 1 && jQuery(pocket).text() == "x"){
                    score += 0;
                } else if(val == 1 && jQuery(pocket).text() == "0"){
                    score += 2;
                }
                if(val == 1) i++;
                if(i == 3) return false;
            });
            totalScore[d_key] = score;
        });


        function descending( a, b ) {
                return b - a;
            }
        totalScore.sort( descending );


    }
4

2 回答 2

-1

您仍在使用对象而不是数组。请记住,在 JavaScript 中,一切都是对象。所以如果你定义一个数组:

var arr = [];

然后向其中添加一个项目:

arr["arr0"] = 1;

您的数组的长度为 0,但您的数组对象将有一个名为arr0. 这当然意味着您仍然无法对“数组”进行排序。

一个可能的解决方法是用包含原始键和值的对象填充数组。所以totalScore[d_key] = score;你可以写:

totalScore.push({key: d_key, value: score});

现在您可以编写一个适当的排序函数:

function descending(a, b) {
    return b.value - a.value;
}
于 2013-07-15T22:04:34.920 回答
-1

编辑(问题的错误答案)

尝试 :

totalScore.sort();
totalScore.reverse();
于 2013-07-15T21:48:47.480 回答