array.sort 超过一个值

array.sort by more than one value

我有一个数组变量,由对象填充。 我需要按 array[i].target; 对这个数组进行主要排序;然后通过 array[i].weaponPriority 辅助 我可以按一个值对数组进行排序,但不幸的是我无法理解如何进一步优化它。

请指教

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();

您可以尝试这样的操作:

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