1 function getRandomCode(length) { 2 if (length > 0) { 3 var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; 4 var nums = ""; 5 for (var i = 0; i < length; i++) { 6 var r = parseInt(Math.random() * 61); 7 nums += data[r]; 8 } 9 return nums; 10 } else { 11 return false; 12 } 13 } 14 var res = getRandomCode(32); 15 console.log(res);
length參數為生成隨機序列號的字符長度;
Math.random(),返回介於 0(包含) ~ 1(不包含) 之間的一個隨機數。
取得介於 1 到 10 之間的一個隨機數:Math.floor((Math.random()*10)+1);
取得介於 1 到 100 之間的一個隨機數:Math.floor((Math.random()*100)+1);
取得min(包含)~ max(不包含)之間的數字:Math.floor(Math.random() * (max - min) ) + min;
取得min(包含)~ max(包含)之間的數字:Math.floor(Math.random() * (max - min + 1) ) + min;