mardi 18 août 2020

How to create a javascript function that randomly generates a number between 1 and 12, and returns the name of the corresponding month

The issue I am having with the below code is that it yields "1" or "January" each time instead of, I guess, using the randomly generated number between 1-12. My initial thought is that the issue is that some piece is not allowing the Math.random method to properly execute, so it is defaulting to 1? The Math.random function works perfectly until I add the "if" statements. I think I may be calling them incorrectly.

note: I believe I could create a loop or something to return the corresponding month, but I am trying to keep the code as basic as possible as I am still learning the fundamentals.

Any help or insight is very welcome. Thanks!

function randomNum(min, max) {
  var result = Math.floor(Math.random() * (max - min + 1) + min);
  if (result = 1) {
    return "January";
  } else if ((result = 2)) {
    return "February";
  } else if ((result = 3)) {
    return "March";
  } else if ((result = 4)) {
    return "April";
  } else if ((result = 5)) {
    return "May";
  } else if ((result = 6)) {
    return "June";
  } else if ((result = 7)) {
    return "July";
  } else if ((result = 8)) {
    return "August";
  } else if ((result = 9)) {
    return "September";
  } else if ((result = 10)) {
    return "October";
  } else if ((result = 11)) {
    return "November";
  } else if ((result = 12)) {
    return "December";
  }
  return result;
}

console.log(randomNum(1, 12));

Aucun commentaire:

Enregistrer un commentaire