0

When I Input the first number to be for example 5 and the second Number to be like 10 I get undefined. I tried alert(array); to see the contents of it but there was nothing and hence undefined. It works for other numbers like 1 to 9. Why does it give me an undefined value from range 5 to 10? I just want to make a random number chooser where you will input the first number and the second number and a random number will be given to you?

function promptUser() {
 var first = prompt("First number?");
 var second = prompt("Second number?");
 var array = [];
 //Make a range from First number to last number then choose a random number
 for (x = first; x <= second; x++) {
 array.push(x);
 }
 alert(array);
 randomInt = Math.floor(Math.random() * array.length);
 alert("The random number is " + array[randomInt]);
}

Satpal
134k13 gold badges168 silver badges171 bronze badges
asked Jan 16, 2017 at 8:53

3 Answers 3

3

prompt() returns the result in string literal, you need to use parseInt() or other methods to convert string to Number.

var first = parseInt(prompt("First number?"), 10);
var second = parseInt(prompt("Second number?"), 10);
var array = [];
for (x = first; x <= second; x++) {
 array.push(x);
}
randomInt = Math.floor(Math.random() * array.length);
console.log(array, randomInt, "The random number is " + array[randomInt]);

Additionally, alert() is not a debugging tool, Learn to use Console

answered Jan 16, 2017 at 8:56
Sign up to request clarification or add additional context in comments.

Comments

0

your first number is being treated as string needed to be parsed as int

function promptUser(){
 var first = prompt("First number?");
 var second = prompt("Second number?");
 var array = [];
 <!--Make a range from First number to last number then choose a random number-->
 for (x = parseInt(first); x <= parseInt(second); x++){
 array.push(x);
 }
 console.log(array);
 randomInt = Math.floor(Math.random()*array.length);
 console.log(randomInt);
 alert("The random number is " + array[randomInt]);
 }
 promptUser();
answered Jan 16, 2017 at 9:00

Comments

0

Use:

var first = parseInt(prompt("First number?"));
var second = parseInt(prompt("Second number?"));

instead of:

var first = prompt("First number?");
var second = prompt("Second number?");

prompt returns string

answered Jan 16, 2017 at 9:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.