Javascript 使用函数按字母顺序对字符串进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30912663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort a string alphabetically using a function
提问by Mike. D
Imagine you were given a string and you had to sort that string alphabetically using a function. Example:
想象一下,给定了一个字符串,您必须使用函数按字母顺序对该字符串进行排序。例子:
sortAlphabets( 'drpoklj' ); //=> returns 'djklopr'
What would be the best way to do this?
什么是最好的方法来做到这一点?
回答by Tushar
回答by marvinhagemeister
Newer browsers support String.prototype.localeCompare()which makes sorting utf8
encoded strings really simple. Note that different languages may have a different order of characters. More information on MDN about localCompare.
较新的浏览器支持String.prototype.localeCompare()这使得对utf8
编码字符串进行排序非常简单。请注意,不同的语言可能具有不同的字符顺序。有关 localCompare 的 MDN 的更多信息。
function sortAlphabet(str) {
return [...str].sort((a, b) => a.localeCompare(b));
}
console.log(sortAlphabet("drpoklj")); // Logs: "djklopr"
If you only have to support ascii strings then the default sorting implementation will do.
如果您只需要支持 ascii 字符串,那么默认的排序实现就可以了。
function sortAlphabet(str) {
return [...str].sort();
}
回答by T.J. Crowder
As previous answers have shown, you convert the string to an array of single-character strings, sort that, and then recombine it into a string. But, using split
isn't the best practice way to do that first step, because a JavaScript string is a series of UTF-16 code units with invalid surrogate pairs tolerated, and split("")
splits up surrogate pairs into their individual code units, potentially separating them, thus breaking the code point(loosely: character) they're supposed to form as a pair. So if you have an emoji in the string (for instance) or any of hundreds of thousands of characters in non-Western scripts, those can get broken.
正如前面的答案所示,您将字符串转换为单字符字符串数组,对其进行排序,然后将其重新组合成一个字符串。但是,使用split
并不是第一步的最佳实践方法,因为 JavaScript 字符串是一系列 UTF-16 代码单元,可以容忍无效的代理对,并将split("")
代理对拆分为各自的代码单元,可能会将它们分开,因此打破了他们应该形成一对的代码点(松散地:字符)。因此,如果您在字符串中包含表情符号(例如)或在非西方脚本中包含数十万个字符中的任何一个,则这些字符可能会损坏。
In ES5 and earlier, correctly splitting the string required that you detect and handle surrogate pairs to ensure they stayed together, which was a bit of a pain and involved checking charCodeAt
for specific ranges of values.
在 ES5 及更早版本中,正确拆分字符串需要您检测和处理代理对以确保它们保持在一起,这有点麻烦并且涉及检查charCodeAt
特定范围的值。
As of ES2015+, it's really easy: You just use the string's iterator, which is defined to provide each code pointin the string, whether that's a single code unit or two. To get an array of the code points, you can use the iterator via spread notation ([...str]
) or Array.from
(Array.from(str)
).
从 ES2015+ 开始,这真的很简单:您只需使用字符串的迭代器,它被定义为提供字符串中的每个代码点,无论是单个代码单元还是两个代码单元。要获取代码点数组,您可以通过扩展符号 ( [...str]
) 或Array.from
( Array.from(str)
)使用迭代器。
So using that, we get:
所以使用它,我们得到:
function sortAlphabets(str) {
return [...str].sort((a, b) => a.localeCompare(b)).join("");
}
Live Example:
现场示例:
// Using the iterator
function sortAlphabets(str) {
return [...str].sort((a, b) => a.localeCompare(b)).join("");
}
// Using split("")
function sortAlphabetsUsingSplit(str) {
return str.split("").sort((a, b) => a.localeCompare(b)).join("");
}
const str = "????????";
console.log("Original string : " + str);
console.log("Using the iterator : " + sortAlphabets(str));
console.log("Using split('') : " + sortAlphabetsUsingSplit(str));
Note how using split
, some of the characters have gotten mangled.
请注意如何使用split
,某些字符已被损坏。