2013-11-09 26 views
0

我想按降序排列數組。未知的Javascript錯誤

這是我的當前代碼:

for(var i = 0; i < scoresArray.length; i){ 
function swap(a, b) { 
      var temp = scoresArray[a].score; 
      scoresArray[a] = scoresArray[b].score; 
      scoresArray[b] = temp; 
} 
    for(var x = 0; x < scoresArray.length; x++){ 
     if(scoresArray[x].score < scoresArray[++x].score){ 
      console.log(x); 
      swap(x, ++x); 
     } 
    } 
} 
return scoresArray.content; 

這是輸入數組:

[ 
    { url: 'www.lboro.ac.uk', score: 6 }, 
    { url: 'www.xyz.ac.uk', score: 3 }, 
    { url: 'www', score: 8 } ] 

這(應該是)輸出數組:

[{ url: 'www.xyz.ac.uk', score: 3 }, 
    { url: 'www.lboro.ac.uk', score: 6 }, 
    { url: 'www', score: 8 } ] 
+4

使用[中的Array.sort(的compareFunction)](HTTPS://developer.mozilla。 org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)將使這更容易。 – Douglas

+1

你想把它分類爲什麼?分數還是Url?你提到的降序...得分似乎是在升序在你的輸出? – ajc

回答

2

像@Douglas所述,使用array.sort(compareFunction)使這更容易:

var scoresArray = [ 
    { url: 'www.lboro.ac.uk', score: 6 }, 
    { url: 'www.xyz.ac.uk', score: 3 }, 
    { url: 'www', score: 8 } ]; 
scoresArray.sort(function(a,b) { 
    return a.score - b.score; 
}); 

請注意,由於scoresArray[i].score是數字,因此您可以使用return a.score - b.score。在更一般的情況下(例如,如果他們的字符串),你可以使用

scoresArray.sort(function(a,b) { 
    if(a.score > b.score) return 1; 
    if(a.score < b.score) return -1; 
    return 0; 
}); 
+2

你的'.sort'函數可以是'return b.score - a.score;'來獲得反向排序。你不需要任何「if」語句。 – jfriend00

1

的交換功能無法正常工作,它只需將比分號替換scoresArray值。知道++x更改x的值也很重要。我想你的意思是x + 1

這大致工作原理:

var scoresArray = [ 
    { url: 'www.lboro.ac.uk', score: 6 }, 
    { url: 'www.xyz.ac.uk', score: 3 }, 
    { url: 'www', score: 8 } ]; 

function swap(a, b) { 
    var temp = scoresArray[a]; 
    scoresArray[a] = scoresArray[b]; 
    scoresArray[b] = temp; 
} 

for(var i = 0; i < scoresArray.length; i++) { 
    for(var x = 0; x < scoresArray.length - 1; x++) { 
     if (scoresArray[x].score > scoresArray[x + 1].score) { 
      swap(x, x + 1); 
     } 
    } 
} 

console.log(scoresArray); 

但它會更好,請使用Array.sort:

var scoresArray = [ 
    { url: 'www.lboro.ac.uk', score: 6 }, 
    { url: 'www.xyz.ac.uk', score: 3 }, 
    { url: 'www', score: 8 } ]; 

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

console.log(scoresArray); 
+2

您的.sort函數只能是'返回b.score - a.score;'來獲得反向排序。你不需要任何「if」語句。 – jfriend00

+0

@ jfriend00,是的,很好的建議。我已經更新了答案。 – Douglas