在 JavaScript 中按字母顺序反向排序的字符串
javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/18 3:24:17
我们需要编写一个 JavaScript 函数,该函数接受一个小写字符串并按相反的顺序对其进行排序,即 b 应该在 a 之前,c 在 b 之前,依此类推。
例如:
如果输入字符串是 −
const str = "hello";
那么输出应该是 −
const output = "ollhe";
其代码为 −
const string = 'hello';
const sorter = (a, b) => {
const legend = [-1, 0, 1];
return legend[+(a < b)];
}
const reverseSort = str => {
const strArr = str.split("");
return strArr
.sort(sorter)
.join("");
};
console.log(reverseSort(string));
以下是控制台上的输出 −
ollhe
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

