Home  >  Article  >  Web Front-end  >  JavaScript generates m-digit random numbers based on time, with a maximum of 13 digits_javascript skills

JavaScript generates m-digit random numbers based on time, with a maximum of 13 digits_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:32:341654browse

Generate m-digit random number based on time, with a maximum of 13-digit random number, and there is no guarantee that the first bit is not 0

function ran(m) {
m = m > 13 ? 13 : m;
var num = new Date().getTime();
return num.toString().substring(13 - m);
}
console.log(ran(5));

According to the random number generated by Math's random function, m digits are intercepted. The generated random number does not exceed 16 digits at most, and the first bit is guaranteed not to be 0

function rand(m) {
m = m > 16 ? 16 : m;
var num = Math.random().toString();
if(num.substr(num.length - m, 1) === '0') {
return rand(m);
}
return num.substring(num.length - m);
}
console.log(rand(5));

Generated based on Math’s random function, there is no limit on the number of digits, and the first bit is not 0

function rando(m) {
var num = '';
for(var i = 0; i < m; i++) {
var val = parseInt(Math.random()*10, 10);
if(i === 0 && val === 0) {
i--;
continue;
}
num += val;
}
return num;
}
console.log(rando(5));
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn