抽奖功能无法运行:JavaScript代码问题排查求助
Alright, let's dig into why your raffle code isn't working and fix it up. There are a handful of critical issues here that are causing everything to break:
Infinite Loop Chaos
Your nesteddo-whileandforloops are completely misconfigured. Thedo-whileincrementsievery iteration, but theforloop's condition checksi<=names.lengthand never updatesior has a proper termination condition. This will lock up your browser in an infinite loop before it ever gets to the raffle logic.Array Index Out-of-Bounds
Inside theforloop, you start withcount=0, immediately runcount++, then accessnames[count]. Since arrays are 0-indexed, whencounthitsnames.length(3 in your example),names[3]isundefined—that's an invalid index.Broken Random Number Generation
TheGetRandomInt()function usesMath.floor(Math.random()*i+1), which is wrong on two counts:iends up beingnames.length + 1after your loop runs, so you're generating numbers outside the array's valid index range.- You're starting at 1, which skips the first element in the array (index 0) entirely.
Case-Sensitive Variable Mistake
InCallWinner(), you definevar ID = GetRandomInt();but then referenceid(lowercase) later. JavaScript is case-sensitive, soidis treated as an undefined variable here.Messy
document.writeUsage
Your original loop spams duplicate output, and ifCallWinner()runs after the page loads,document.writewill overwrite the entire page—hardly ideal for a raffle display.
Fixed Code
Here's a cleaned-up, working version with clear logic:
// Raffle participant list const names = ["Stefon", "Garret", "Brandon"]; // Generate a valid array index (0 to names.length - 1) function getRandomInt() { return Math.floor(Math.random() * names.length); } // Assign and display raffle IDs (1-based for user-friendliness) function assignRaffleIds() { names.forEach((name, index) => { const raffleId = index + 1; document.write(`${name} has been assigned to the raffle ID, ${raffleId}<br>`); }); } // Pick and announce the winner function callWinner() { const winnerIndex = getRandomInt(); const winnerName = names[winnerIndex]; const winnerId = winnerIndex + 1; // Match the 1-based ID we displayed earlier document.write(`<hr>${winnerName} has won with the ID of ${winnerId}!`); } // Run the workflow: assign IDs first, then draw the winner assignRaffleIds(); callWinner();
Key Improvements:
- Replaced the chaotic nested loops with
forEachfor clean, readable ID assignment. - Fixed the random number generator to produce valid array indexes every time.
- Corrected the variable case mismatch to avoid undefined errors.
- Split functionality into separate, single-purpose functions for better maintainability.
- Ensured no infinite loops and valid array access at all times.
内容的提问来源于stack exchange,提问作者Strount

