如何通过循环构建字符串?JavaScript代码优化问询
Hey there! Let's get this sorted so you can collect and display all the words entered during your game. Here's a breakdown of the issues and the fixed solution:
What's Wrong with the Original Code
Your current code has a couple of key issues:
- The
game2variable is declared inside the loop, so it gets overwritten every time the loop runs—only the last input gets saved. - There's a syntax error:
if (prompt === 'Yes');has an extra semicolon that breaks the if logic, plus you're checkingpromptinstead of the actual variablegamewhere you stored the first user response. - The loop logic doesn't properly track whether the user wants to keep playing on the first run.
Fixed Code
Here's the revised version that collects all words and outputs them as a space-separated string:
let game = prompt('Do you want to play?'); let words = []; // Array to store all entered words if (game === 'Yes') { do { let userWord = prompt('Enter your word.'); words.push(userWord); // Add each new word to the array game = prompt('Do you want to play again?'); } while (game !== 'No'); } // Convert the array to a space-separated string and log it console.log("Your words are: " + words.join(' '));
Key Changes Explained
- Array for storage: We use an array
wordsto keep track of every word the user enters—instead of overwriting a single variable, wepush()each new word into the array. - Fixed if logic: Removed the extra semicolon from the if statement and check the correct variable
gameto start the game only if the user says "Yes". - Clean loop flow: Updated the loop to reassign
gamewith the "play again" prompt, so the loop condition correctly checks if the user wants to stop. - Join array to string: The
join(' ')method takes all elements in the array and combines them into one string, separated by spaces—perfect for your desired output format.
内容的提问来源于stack exchange,提问作者Mohammed Fahad
相关产品推荐
相关产品推荐

