ShootingBlanks Posted October 10, 2007 Share Posted October 10, 2007 Hello. Please note the following code, placed on its own between the BODY tags of a webpage: <script type="text/javascript"> var outputNumber; var numbersGenerated; var startNumber = prompt("Pick a number to start with",""); var endNumber = prompt("Pick a number to end with","") var numberCount = prompt("How many random numbers would you like generated?",""); var numberDifference = Math.abs(endNumber-startNumber); for (numbersGenerated = 0; numbersGenerated < numberCount; numbersGenerated++) { outputNumber = (Math.floor(Math.random() * numberDifference) + 50); document.write(numbersGenerated+1 + ". " + outputNumber + "<br />"); } </script> Enter "50" in the first prompt, then "75" in the second, then "50" in the third. The code seems to work as I'd like (showing 50 random numbers bewtween 50 & 75)... NOW, go ahead and change this line: outputNumber = (Math.floor(Math.random() * numberDifference) + 50); To this: outputNumber = (Math.floor(Math.random() * numberDifference) + startNumber); And the code totally messes up. But "startNumber" IS "50", so I'm not understanding why changing it from a number to a variable would yield such different results!... Quote Link to comment Share on other sites More sharing options...
roopurt18 Posted October 10, 2007 Share Posted October 10, 2007 It's because startNumber is a String object and + means concatenate. outputNumber = (Math.floor(Math.random() * numberDifference) + parseInt(startNumber)); Quote Link to comment Share on other sites More sharing options...
ShootingBlanks Posted October 10, 2007 Author Share Posted October 10, 2007 That's it - thanks! I'm new at JS (if you couldn't tell!!!) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.