2015-01-13 29 views
0

我有一個數組變量,由對象填充。 我需要通過數組[i] .target對這個數組進行排序;然後由數組[i] .weaponPriority 次要我可以排序一個值的數組,但不幸我不知道如何我可以進一步細化它。array.sort不止一個值

請指教。

var ships = [] 

function Ship(name, target, priority){ 
this.name = name; 
this.target = target; 
this.id = ships.length; 
this.weaponPriority = priority; 
} 

var ship = new Ship("Alpha", 10, 3); 
ships.push(ship); 
var ship = new Ship("Beta", 10, 1); 
ships.push(ship); 
var ship = new Ship("Gamma", 10, 3); 
ships.push(ship); 
var ship = new Ship("Delta", 15, 2); 
ships.push(ship); 


function log(){ 
for (var i = 0; i < ships.length; i++){ 
    var shippy = ships[i]; 
    console.log(shippy.name + " ---, targetID: " + shippy.target + ", weaponPrio: " + shippy.weaponPriority);    
} 


ships .sort(function(obj1, obj2){ 
... 
}); 

log(); 

回答

5

你可以嘗試這樣的事:

function(obj1, obj2){ 
    // We check if the target values are different. 
    // If they are we will sort based on target 
    if(obj1.target !== obj2.target) 
     return obj1.target-obj2.target 
    else // The target values are the same. So we sort based on weaponPriority 
     return obj1.weaponPriority-obj2.weaponPriority; 
} 

您將這個函數傳遞給sort