Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article is mainly to record the problems in the work and write down their own solutions. The sun arches a pawn.

Welcome the boss to correct, optimize, troll to bypass ~~

Random number generation

While generating random numbers between 0 and 9 is easy, simple business requirements can be met by using the Math object method math.floor (math.random () * 10).

If you need a random number between 0 and 99, you can set the multiplier to 100 as follows, but between 10 and 99?

Math.floor(Math.random() * 100);
Copy the code

So I just want two numbers, no more, no less.

Because math.random () this method might randomly produce results like 0.01, 0.001, 0.0001… These numbers.

That is to say, in the random 0.01, then use the above method will appear less a situation.

As a CV programmer, I figured other developers would be in this situation. Go baidu first then 🥱

Manual DOGE, there is a solution, and that’s it:

function randomNum(n) {
  let value = ' ';
  for (let i = 0; i < n; i++) {
    value += Math.floor(Math.random() * 10);
  }
  return value;
}
Copy the code

This function works simply by generating a random number using the method at the beginning of the article and then concatenating it with a string.

The number of digits is enough, but the format is not ideal. So this function also does what you need, but only in most cases.

Because it is a string concatenation format, it may contain cases that begin with the number 0. If you need to do string concatenation, you can use this format.

For business reasons, I need to convert to a numeric type. I’m not talking about converting with Number(), which would still be the wrong Number.

Improvement ideas

Returning to our original problem, math.random () might randomly produce 0.01 or less.

So, the easiest way to do this is just to make a judgment before returning

When you need a digit, the return value must be an integer less than 10.

When you need a two-digit number, the return value must be an integer less than 100 and greater than or equal to 10.

.

So if the final value returned is less than the given number of digits 10^(n-1), rerun the function is very hot 🌶

function _randomInt(n) {
  if (n <= 0) return -1;  // Only positive integers can be entered
  const limit = Math.pow(10, n);
  let value = Math.floor(Math.random() * limit);  // Round down with random number to avoid extra digits
  if (value < (limit / 10) && value ! = =0) {  // We don't need this function when we get a digit, but we still want to pass the child 0
    return _randomInt(n);
  }
  return value
}
Copy the code