写一个方法,将字符串中的单词倒转后输出,如:`my love` -> `ym evol`
function reverseWords(str) {
// 1. Split the string into words
const words = str.split(" ");
// 2. Reverse each word
const reversedWords = words.map(word => {
return word.split("").reverse().join("");
});
// 3. Join the reversed words back into a string
return reversedWords.join(" ");
}
// Example usage:
const inputString = "my love";
const reversedString = reverseWords(inputString);
console.log(reversedString); // Output: ym evol
// More concise version using chaining:
const reverseWordsConcise = (str) => str.split(" ").map(word => word.split("").reverse().join("")).join(" ");
console.log(reverseWordsConcise("hello world")); // Output: olleh dlrow
// Handling multiple spaces and edge cases (empty string, single word, leading/trailing spaces):
function reverseWordsRobust(str) {
if (!str) return ""; // Handle empty string
return str.trim() // Remove leading/trailing spaces
.split(/\s+/) // Split by one or more spaces
.map(word => word.split("").reverse().join(""))
.join(" ");
}
console.log(reverseWordsRobust(" hello world ")); // Output: olleh dlrow
console.log(reverseWordsRobust(" single")); // Output: elgnis
console.log(reverseWordsRobust("")); // Output: ""
// Using a for loop for reversal (slightly more performant for very large words):
function reverseWordWithLoop(word) {
let reversed = "";
for (let i = word.length - 1; i >= 0; i--) {
reversed += word[i];
}
return reversed;
}
function reverseWordsWithLoop(str) {
if (!str) return "";
return str.trim()
.split(/\s+/)
.map(word => reverseWordWithLoop(word))
.join(" ");
}
console.log(reverseWordsWithLoop("hello world")); // Output: olleh dlrow
This provides several versions of the function:
reverseWords
: Basic implementation.reverseWordsConcise
: A more concise version using method chaining.reverseWordsRobust
: Handles multiple spaces, leading/trailing spaces, and empty strings. This is generally the most robust solution.reverseWordsWithLoop
: Uses afor
loop for character reversal within each word. This can be slightly more performant than usingsplit("").reverse().join("")
for very large words, though the difference is usually negligible.
Choose the version that best suits your needs and coding style. The robust version is recommended for most real-world applications. The for
loop version might be preferred if performance is a critical concern and you're dealing with potentially very long words.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异