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
wordvariable is declared inside theforloop, so it can’t be accessed outside the loop when you try to updateresult.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
Havetohaveafter 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 (turningHaveintohaveto match your exampleI 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
相关产品推荐
相关产品推荐

