array.sort由多个值组成

时间:2015-01-13 11:36:49

标签: javascript arrays sorting

我有一个由对象填充的数组变量。 我需要通过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();

1 个答案:

答案 0 :(得分: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