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

JavaScript实现句子单词按2、1、3顺序重排及代码调试求助

Fixing Sentence Reordering in JavaScript

Hey there! Let's get your code working properly—you’ve already started with the right ideas (splitting lines and words), just a few adjustments are needed to make it handle the reordering correctly.

First, let's break down the issues in your current code:

  • The word variable is declared inside the for loop, so it can’t be accessed outside the loop when you try to update result.value.
  • You’re using incorrect array indices: when you split a line like Have I Banana, the resulting array is ["Have", "I", "Banana"], so indices are 0, 1, 2 (not 1, 2, 3).
  • You’re not adding spaces between the reordered words, and you’re not building the result incrementally inside the loop.
  • You need to adjust the capitalization of the first word to match your example (changing Have to have after reordering).

Here’s the corrected code with explanations:

var text = document.getElementById('mytext');
var result = document.getElementById('myresult');
var lines = text.value.split('\n');
result.value = ''; // Initialize result as empty string

for (var i = 0; i < lines.length; i++) {
  var line = lines[i].trim(); // Trim whitespace to handle empty lines
  if (!line) continue; // Skip empty lines to avoid errors
  
  var words = line.split(' '); // Split line into array of words
  if (words.length === 3) { // Make sure we have exactly 3 words
    // Reorder: 2nd word (index 1) → 1st word (index 0, lowercase) → 3rd word (index 2)
    var reordered = `${words[1]} ${words[0].toLowerCase()} ${words[2]}`;
    result.value += reordered + '\n'; // Add each reordered line to result with newline
  } else {
    // Handle lines that don't have 3 words (optional)
    result.value += line + '\n';
  }
}
// Remove the extra newline at the end
result.value = result.value.trim();

Key points explained:

  • line.trim() removes extra spaces/newlines from each line, so empty lines are treated properly.
  • We check if the line has exactly 3 words before reordering to avoid errors from malformed lines.
  • ${words[1]} ${words[0].toLowerCase()} ${words[2]} handles the reordering and capitalization (turning Have into have to match your example I have Banana).
  • We build the result incrementally inside the loop, adding each reordered line followed by a newline.
  • Finally, trim() removes any trailing newline that might be added at the end.

Testing with your example input:

If mytext contains:

Have I Banana
Have I Apple
Have I Car

The myresult will output:

I have Banana
I have Apple
I have Car

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:32:47