R Nadhiban
R Nadhiban

Reputation: 3

Choosing a random value from an array gives undefined

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]);
}

Upvotes: 0

Views: 72

Answers (3)

Ankush G
Ankush G

Reputation: 1081

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

Upvotes: 0

Mitesh Pant
Mitesh Pant

Reputation: 542

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();

Upvotes: 0

Satpal
Satpal

Reputation: 133403

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

Upvotes: 3

Related Questions