試煉
- 寫一個函數(shù),返回從min到max之間的 隨機(jī)整數(shù),包括min不包括max
function random(min,max) {
return min + Math.floor(Math.random()*(max-min));
}
console.log(random(2,12))
寫一個函數(shù),返回從min都max之間的 隨機(jī)整數(shù),包括min包括max
function random(min,max) {
return min + Math.ceil(Math.random()*(max-min));
}
console.log(random(2,10))
寫一個函數(shù),生成一個長度為 n 的隨機(jī)字符串,字符串字符的取值范圍包括0到9,a到 z,A到Z。
function random(min,max) {
return min + Math.floor(Math.random()*(max-min));
}
function getRandStr(len){
var dict= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
str = ''
for (var i=0; i<len; i++) {
str += dict[random(0,62)]
} return str;
}
var newstr = getRandStr(10); // 0a3iJiRZap
console.log(newstr)
寫一個函數(shù),生成一個隨機(jī) IP 地址,一個合法的 IP 地址為 0.0.0.0~255.255.255.255
function random(min,max) {
return min + Math.floor(Math.random()*(max-min));
}
function getRandIP(){
var arr = []
for (var i=0; i<4; i++) {
arr.push(random(0,256))
} return arr.join('.')
}
var ip = getRandIP()
console.log(ip)
寫一個函數(shù),生成一個隨機(jī)顏色字符串,合法的顏色為#000000~ #ffffff
function random(min,max) {
return min + Math.floor(Math.random()*(max-min));
}
function getRandColor(){
dict = '0123456789abcdef'
var str =''
for(var i=0; i<6; i++) {
str +=dict[random(0,16)]
} return '#'+str
}
var color = getRandColor()
console.log(color)