问题描述
在不使用内置函数 (.reverse()
, .charAt) 的情况下,如何在 JavaScript 中就地反转字符串,将其传递给带有 return 语句的函数()
等)?
How do you reverse a string in-place in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse()
, .charAt()
etc.)?
推荐答案
只要您处理简单的 ASCII 字符,并且您乐于使用内置函数,这将有效:
As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:
function reverse(s){
return s.split("").reverse().join("");
}
如果您需要支持 UTF-16 或其他多字节字符的解决方案,请注意此函数将提供无效的 unicode 字符串,或看起来很有趣的有效字符串.您可能需要考虑这个答案.
If you need a solution that supports UTF-16 or other multi-byte characters, be aware that this function will give invalid unicode strings, or valid strings that look funny. You might want to consider this answer instead.
[...s] 是 Unicode 感知的,一个小的编辑给出:-
[...s] is Unicode aware, a small edit gives:-
function reverse(s){
return [...s].reverse().join("");
}
这篇关于如何在 JavaScript 中就地反转字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!