2012-02-03 61 views
0

我想通过score值对此对象进行排序,因此我可以填充高分表。找到这种排序方法,它适用于公式中的-,从最小排序到最高排序可行,但是当我尝试使用+将其排序时,它不起作用。我很困惑..为什么这个对象数组的排序失败?

JS:

scores = [ 
     {"n":"Arne", "score":700}, 
     {"n":"Bertil", "score":430}, 
     {"n":"Carl", "score":901}, 
     {"n":"David", "score":30}, 
     {"n":"Eric", "score":23}, 
     {"n":"Frida", "score":118}, 
     {"n":"Greg", "score":221}, 
     {"n":"Hulk", "score":543} 
     ]; 

scores.sort(function(a, b) { 
return a.score + b.score; 
}); 

//add rows to table from scores object 
var t = document.getElementById('table'); 
for (var j in scores) { 

     var r = document.createElement('tr') 
     r.innerHTML = '<td><span></span></td><td>'+scores[j].n+'</td><td>'+scores[j].s+'</td>' 
     t.appendChild(r); 
} 

回答

3

你提到你试图扭转排序,最初涉及减法。

因此,我认为这是公平的假设,你原来的排序是这样的...

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

如果你想在相反的方向进行排序,只是扭转减法的顺序:

scores.sort(function(a, b) { 
    return b.score - a.score; 
}); 
+0

宾果!谢谢 – jenswirf 2012-02-03 15:37:45

0

您的排序函数应该返回positive , 0 , or negative values

你可能想那里添加一些数字是错误的。

试一下:

http://jsbin.com/icojaz/edit#javascript,html

它按分数。

+0

技术上你的比较器导致未定义的排序顺序,请参阅15.4.4.11的规范,你的函数打破了这些一致性要求的一半。 – davin 2012-02-03 15:40:20

-1

根据http://www.w3schools.com/jsref/jsref_sort.asp你可以看到,你只是像这样反转输入参数:return a.score - b.score;

+0

-1参考w3schools。请访问http://w3fools.com/ :-) – 2012-02-03 15:54:55

+0

感谢您的信息。 – 2012-02-06 13:00:07