MDN example (of Math.random()): could it be parseI

2019-09-12 00:01发布

问题:

I was reading a JavaScript tutorial and searching for functions on MDN website when I stumbled across this example of Math.random():

function getRandomIntInclusive(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

While I understand that Math.floor chooses the biggest number and with that erases all numbers that have decimal values, I already learnt another function called parseInt() which just deletes all of the numbers after point. So, what's the difference between those two? Couldn't I just use

function getRandomInclusive(min, max) {
return parseInt(Math.random() * (max - min + 1)) + min;
}

instead? I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4, but it's not really important for random number generator as I understand (if you know any examples of when it would be important, please tell me!) So, there's still not much of a difference in this case?

回答1:

parseInt parses a string into an integer, reading only digits at the beginning of that string. It is not appropriate to use to round a number to an integer. The number will be converted to a string first, sometimes with unexpected results:

var num = 1000000000000000000000;
parseInt(num) // 1, because the string representation is 1e+21

I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4

You’re thinking of rounding to the nearest whole number, which is what Math.round does. Math.floor always rounds down.



回答2:

The clear difference is that Math.floor is a function that works on numbers while parseInt is a function that takes a string. You don't want to use the latter here as we deal with random numbers.

If you are unsure about the rounding mode, compare Math.floor, Math.round and Math.ceil.



回答3:

Here's an example where their behaviour differs drastically: negative numbers.

Math.floor(-2.5) -> -3
parseInt(-2.5) -> -2

The semantic difference pointed out in other answers, however, is probably more important. Even if it does work for your particular and specific use-case, it's best to pick the one with the correct semantics. (There are countless other ways to return a seemingly random integer from a function, you should pick the one that's the least likely to make your code hard to maintain.)