gpt4 book ai didi

javascript - 替换 > 和 < 运算符

转载 作者:太空宇宙 更新时间:2023-11-04 15:42:11 24 4
gpt4 key购买 nike

是否有大于/小于运算符(<,>)的替代品?

我试图在这里按降序对数组进行排序,但我无法在我正在工作的环境中使用运算符。

这是我用来按降序对数组中的字符串进行排序的代码:

// descending order
animals.sort(function (a, b) {
if (a > b) {
return -1;
}
if (b > a) {
return 1;
}
return 0;
});
console.log(animals);
// ["elephant", "dog", "cat", "bee", "ant"]

最佳答案

您可以使用localeCompare函数

var animals = ["dog", "cat", "ant", "bee", "elephant"];

animals.sort(function (a, b) {
return -a.localeCompare(b);
});

console.log(animals);

关于javascript - 替换 > 和 < 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43786118/

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