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

如何通过循环构建字符串?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 game2 variable 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 checking prompt instead of the actual variable game where 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 words to keep track of every word the user enters—instead of overwriting a single variable, we push() each new word into the array.
  • Fixed if logic: Removed the extra semicolon from the if statement and check the correct variable game to start the game only if the user says "Yes".
  • Clean loop flow: Updated the loop to reassign game with 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:25:26