JavaScript中pickRandom is not defined报错问题求助
Let’s break down the issues with your code step by step:
1. pickRandom isn’t a built-in function
Most programming languages (including JavaScript, which your syntax resembles) don’t have a native pickRandom function. That’s exactly why you’re seeing the "pickRandom is not defined" error—your runtime has no idea what that function is supposed to do! You’ll need to define it yourself.
2. Trailing comma in the array (minor but avoidable)
Your array has a trailing comma: ['Quacks' , 'eats', 'Hoots', ] While some environments tolerate this, it’s better to remove it to prevent unexpected behavior in older runtimes.
3. Missing spaces in your output string
When you concatenate 'the owl' + word + 'at midnight', you’ll end up with messy output like the owlQuacksat midnight (no spaces around the verb). This is a small formatting issue, but it makes your result unreadable.
4. print might not be the right function
In JavaScript (whether in a browser or Node.js), the standard way to output text is console.log(), not print()—using print() could result in no output because it’s not supported in most JS environments.
Fixed Code
Here’s the corrected version that addresses all these issues:
// First, define the pickRandom function yourself function pickRandom(arr) { // Generate a valid random index for the array const randomIndex = Math.floor(Math.random() * arr.length); return arr[randomIndex]; } var word = pickRandom(['Quacks', 'eats', 'Hoots']); // Use template literals for cleaner, properly spaced string formatting console.log(`the owl ${word} at midnight`);
How It Works
- The
pickRandomfunction usesMath.random()(which returns a number between 0 and 1) multiplied by the array’s length, thenMath.floor()to get a whole-number index. This ensures we always pick a valid element from the array. - Template literals (using backticks
`) let you embed variables directly in strings with proper spacing, avoiding messy concatenation. console.log()ensures your output is visible in the browser’s developer console or Node.js terminal.
内容的提问来源于stack exchange,提问作者Elitezen

