求助:实现按用户输入次数生成随机字符串的JavaScript程序
Fixing Your Random String Generator in JavaScript
Hey there! I see your code got cut off mid-way, and that’s probably a big reason it’s not running. Let’s break down what’s missing and get your random string generator working perfectly.
First, let’s look at your original (truncated) code:
function randomString() { var totalIterations = parseInt(document.getElementById('input').value); var output = document.getElementById('output'); output.innerHTML = ''; var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; var string_length = 8; var randomstri...
The main issues here:
- Your code is incomplete—you started declaring
randomstribut never finished the logic to build the string or loop through the requested iterations. - There’s no loop to generate multiple strings based on the user’s input count.
- You aren’t validating the input (what if the user enters a non-number or negative value?).
Here’s the fixed, complete version:
First, let’s include the full HTML structure to make this work end-to-end (you probably have this already, but it’s good to clarify):
<!-- HTML --> <input type="number" id="input" placeholder="Enter number of strings" min="1"> <button onclick="randomString()">Generate Strings</button> <div id="output"></div>
Now the updated JavaScript:
function randomString() { // Get and validate user input var totalIterations = parseInt(document.getElementById('input').value); var output = document.getElementById('output'); output.innerHTML = ''; // Handle invalid input to avoid errors if (isNaN(totalIterations) || totalIterations < 1) { output.innerHTML = '<p>Please enter a valid positive number!</p>'; return; } var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; var string_length = 8; // Loop to generate the requested number of strings for (var i = 0; i < totalIterations; i++) { var randomString = ''; // Build each individual 8-character random string for (var j = 0; j < string_length; j++) { var randomNum = Math.floor(Math.random() * chars.length); randomString += chars.substring(randomNum, randomNum + 1); } // Add each string to the output (with line breaks for readability) output.innerHTML += '<p>' + randomString + '</p>'; } }
Let’s walk through what’s added:
- Input Validation: We check if the input is a valid positive number—this stops errors from bad user input like letters or negative values.
- Double Loop:
- The outer loop runs exactly
totalIterationstimes (once for each string you want to generate). - The inner loop builds each 8-character string by picking random characters from your
charsset.
- The outer loop runs exactly
- Clean Output: Each generated string is added to the output div with a paragraph tag, so they’re neatly separated and easy to read.
Just copy this code, and it should work exactly as you want—enter a number, click the button, and get that many random 8-character strings!
内容的提问来源于stack exchange,提问作者Tope Kenny
相关产品推荐
相关产品推荐

