Math对象用于执行数学任务。 Math是一个内置对象,不需要创建,可以直接使用。
1.如何得到 0 ~ 1 的随机整数[0,1]?
var random = Math.round(Math.random()); console.log(random);2.如何得到 0 ~ 5 的随机整数[0,5]?
var random = Math.round(Math.random() * (5 - 0)) + 0; console.log(random);3.生成区间随机整数
function randomInt(min, max) { return Math.round(Math.random() * (max - min)) + min; } console.log(randomInt(10, 30)); 写一个函数 randomCode() 生成6位随机验证码(数字、字母(大小)) function randomInt(min, max) { return Math.round(Math.random() * (max - min)) + min; } console.log(randomInt(10, 30)); function randomCode() { // 48-122 >57&&<65 >90&&<97 var arr = [1, 1, 1, 1, 1, 1]; for (var i in arr) { do { var ascii = randomInt(48, 122); } while ((ascii > 57 && ascii < 65) || (ascii > 90 && ascii < 97)); arr[i] = String.fromCharCode(ascii); } return arr.join(''); } console.log(randomCode()); 写一个函数 randomColor 生成随机的十六进制颜色值 # 6个字符 //0 1 2 3 4 5 6 7 8 9 a b c d e f style: .box { width: 200px; height: 100px; } html: <div class="box"></div> script: function randomInt(min, max) { return Math.round(Math.random() * (max - min)) + min; } console.log(randomInt(10, 30)); function randomColor() { var str = '0123456789abcdef'; var col = '#'; for (var i = 0; i < 6; i++) { var index = randomInt(0, 15); col += str[index]; } return col; } console.log(); var box = document.querySelector('.box'); box.style.backgroundColor = randomColor();