mardi 25 août 2015

Better way to use parseInt() to change users' promt() into numbers

I set up a function to ask users a range of numbers, and gave them back a random number. The first try is okay.

// function settings
function getRandom(lower, upper) {
  return Math.floor(Math.random()*(upper-lower+1))+lower;
}

// ask users to give a rang of numbers
var lowerNum = parseInt(prompt("lower number?"));
var upperNum = parseInt(prompt("upper number?"));

document.write(getRandom(lowerNum, upperNum));

However, I thought it would be better to take parseInt() inside the function, so that it would be more clear and semantic.
// function settings
function getRandom(lower, upper) {
  lower = parseInt(lower);
  upper = parseInt(upper);
  return Math.floor(Math.random()*(upper-lower+1))+lower;
}

// ask users to give a rang of numbers
var lowerNum = prompt("lower number?");
var upperNum = prompt("upper number?");

document.write(getRandom(lowerNum, upperNum));

Both blocks of codes can do well and get the same results. But which one is the better practice, or performance when running the program?




Aucun commentaire:

Enregistrer un commentaire