首先是 Math.random()
函數返回一個浮點, 偽隨機數在范圍從0到小於1,也就是說,從0(包括0)往上,但是不包括1(排除1)(應用MDN)
1、寫一個函數生min---max之間的隨機數,包含min和max
for (let i = 0; i < 10; i++) { function sum(min, max) { return Math.round(Math.random() * (max - min) + min); } console.log(sum(10, 20)); }
//隨機打印結果
2 寫一個函數,生成一個隨機顏色字符串,合法的顏色為 #000000--#ffffff
function getRandColor() { const arrColor = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'] let str = '#' for (let i = 0; i < 6; i++) { n = Math.round(Math.random() * 15) str += arrColor[n] } return str } console.log(getRandColor());
//打印結果 #bd1d1b
3.寫一個函數,生成一個長度為 n 的隨機字符串,字符串字符的取值范圍包括 0 到 9,a 到 z,A 到 Z
function getRanStr(n) { const dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const len = dict.length let str = '' for (let i = 0; i < n; i++) { let index = Math.floor(Math.random() *len) str += dict[index] } return str } console.log(getRanStr(6));
4 寫一個函數,生成一個隨機 IP 地址,一個合法的 IP 地址為 0.0.0.0--255.255.255.255
function getRanId() { let ip = [] for (let i = 0; i < 4; i++) { ip += Math.floor(Math.random() * 256) + '.' } return ip } let ip = getRanId() console.log(ip);
5 創建一個數組,數組的長度為10,數組的每一個元素取值范圍為15-30隨機值
let arr = [] function getRandom(min, max) { for (let i = 0; i < 10; i++) { let index = Math.round(Math.random() * (max - min) + min) arr.push(index) } return arr } console.log(getRandom(15, 30));