You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何反转字符串中单词字符且保持顺序?我的JS代码输出异常

Let's break down the issues in your code step by step—you're close to getting the right output, just a few small mistakes tripping you up!

1. Incorrect split separator

You used "\s+" as the split argument, but in JavaScript string literals, \s doesn't mean "whitespace" like it does in regular expressions. It gets interpreted as a literal s character instead. So your code was trying to split the string at occurrences of s+, which don't exist in your input. That means words ended up being an array with just the entire input string as a single element, not three separate words.

Fix this by using a regular expression instead of a string: str.split(/\s+/)—the / delimiters tell JavaScript this is a regex, and \s+ correctly matches one or more whitespace characters.

2. Early return inside the for loop

You put a return statement inside your for loop, which means the function exits immediately after processing the first word. Even if your split was working correctly, you'd only ever get the reversed first word back, not all three.

Move the return outside the loop so the function waits until all words are processed before sending back the result.

3. Missing spaces between reversed words

Your current code concatenates reversed words directly without any spaces, so even if you fixed the first two issues, you'd get dbaehfjdk instead of dba ehf jdk. A cleaner way to handle this is to collect reversed words in an array first, then join them with spaces at the end.

Fixed Code

Here's the corrected version that gives your expected output:

function reverseInPlace(str) {
  // Split string into words using regex for whitespace
  const words = str.split(/\s+/);
  // Reverse each word and collect in a new array
  const reversedWords = words.map(word => word.split('').reverse().join(''));
  // Join reversed words with spaces
  return reversedWords.join(' ');
}

console.log(reverseInPlace("abd fhe kdj")); // Output: dba ehf jdk

Or if you prefer to stick with a for loop instead of map:

function reverseInPlace(str) {
  var words = str.split(/\s+/);
  var result = [];
  for (var i = 0; i < words.length; i++) {
    result.push(words[i].split('').reverse().join(''));
  }
  return result.join(' ');
}

As for why you got jdk fhe dba—my guess is that either your split was accidentally working (maybe you used " " instead of "\s+" but had a reversed loop), or a typo in how you wrote the code. But the fixes above will get you the expected output.

内容的提问来源于stack exchange,提问作者Xinyi Li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:17:19