如何用循环创建连续命名变量并推入数组,实现总字符数达标逻辑
Hey there! Let's work through this problem step by step. You've already got a solid start with manually creating the first 5 word variables and adding them to an array—now we just need to add the logic to keep collecting words until the total character count hits at least 25, while sticking to your word_1, word_2... naming rule.
First: Choose Your Initial Setup
Your original manual declarations work perfectly for the first 5 words, but we can also make that part cleaner with a loop. I've included both options below so you can pick what fits your workflow.
Full Working Code
Here's a complete, tested version that handles both the initial word collection and the dynamic addition until we meet the character requirement:
// Option 1: Create initial 5 words with a loop (cleaner than manual) const wordList = []; for (let i = 1; i <= 5; i++) { // Dynamically generate variables like word_1, word_2... window[`word_${i}`] = prompt("Please enter a word."); wordList.push(window[`word_${i}`]); } // --- OR --- // Option 2: Keep your original manual declarations /* var word_1 = prompt("Please enter a word."); var word_2 = prompt("Please enter a word."); var word_3 = prompt("Please enter a word."); var word_4 = prompt("Please enter a word."); var word_5 = prompt("Please enter a word."); var wordList = []; wordList.push(word_1); wordList.push(word_2); wordList.push(word_3); wordList.push(word_4); wordList.push(word_5); */ // Reusable function to calculate total characters in the array function calculateTotalChars(arr) { let total = 0; for (const word of arr) { total += word.length; } return total; } // Check initial total character count let totalChars = calculateTotalChars(wordList); let nextWordNumber = 6; // Start counting after the initial 5 words // Keep asking for words until we hit the 25-character minimum while (totalChars < 25) { // Create the next sequential word variable (word_6, word_7...) window[`word_${nextWordNumber}`] = prompt(`Need more characters! Current total: ${totalChars}. Please enter another word.`); // Add the new word to our array wordList.push(window[`word_${nextWordNumber}`]); // Update the total character count totalChars = calculateTotalChars(wordList); // Move to the next word number for the next iteration nextWordNumber++; } // Let the user know we're done! alert(`Perfect! Total characters reached: ${totalChars}\nYour words: ${wordList.join(', ')}`);
Key Details Explained
- Dynamic Variable Creation: We use
window[word_${i}]to generate sequential variable names. In browser JavaScript, global variables are properties of thewindowobject, so this trick lets us createword_1,word_2, etc., on the fly instead of writing each one manually. - Reusable Character Count: The
calculateTotalCharsfunction keeps our code clean by handling the sum of word lengths every time we add a new word—no need to repeat that loop logic. - Loop Until Requirement is Met: The
whileloop runs as long as our total character count is less than 25, ensuring we keep collecting words until we hit the minimum.
Quick Edge Case Note
If you want to handle empty inputs (in case a user just hits enter), you can add a quick check inside the while loop to ask for a valid word if the input is empty. For example:
let newWord = prompt(`Need more characters! Current total: ${totalChars}. Please enter another word.`); while (!newWord) { newWord = prompt("Please enter a valid non-empty word!"); } window[`word_${nextWordNumber}`] = newWord;
内容的提问来源于stack exchange,提问作者J Real

