gpt4 book ai didi

Javascript 排序函数。按第一个排序,然后按第二个排序

转载 作者:IT王子 更新时间:2023-10-29 02:59:59 26 4
gpt4 key购买 nike

我有一组对象要排序。每个对象都有两个参数:强度和名称

objects = []
object[0] = {strength: 3, name: "Leo"}
object[1] = {strength: 3, name: "Mike"}

我想先按强度排序,然后按名称字母顺序排序。我正在使用以下代码按第一个参数排序。我该如何按秒排序?

function sortF(ob1,ob2) {
if (ob1.strength > ob2.strength) {return 1}
else if (ob1.strength < ob2.strength){return -1}
return 0;
};

感谢您的帮助。

(我使用 Array.sort() 和前面提到的 sortF 作为传递给它的排序比较函数。)

最佳答案

把你的排序函数扩展成这样;

function sortF(ob1,ob2) {
if (ob1.strength > ob2.strength) {
return 1;
} else if (ob1.strength < ob2.strength) {
return -1;
}

// Else go to the 2nd item
if (ob1.name < ob2.name) {
return -1;
} else if (ob1.name > ob2.name) {
return 1
} else { // nothing to split them
return 0;
}
}

A <>字符串比较字母比较。

关于Javascript 排序函数。按第一个排序,然后按第二个排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9175268/

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