gpt4 book ai didi

javascript - array.sort 按多个值排序

转载 作者:行者123 更新时间:2023-11-28 13:27:29 24 4
gpt4 key购买 nike

我有一个数组变量,由对象填充。我需要按 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

关于javascript - array.sort 按多个值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27921269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com