Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Math #43

Open
yym-yumeng123 opened this issue Sep 8, 2017 · 0 comments
Open

Math #43

yym-yumeng123 opened this issue Sep 8, 2017 · 0 comments

Comments

@yym-yumeng123
Copy link
Owner

1、写一个函数,返回从min到max之间的 随机整数,包括min不包括max

方法一:
function num(min,max){
//   random取值0=<1
  return Math.floor(Math.random()*(max-min))+min
}
console.log(num(1,5))
console.log(num(3,6))
方法二:
function num(min,max){
//   random取值0=<1
  return Math.ceil(Math.random()*(max-min))
}
console.log(num(1,5))
console.log(num(3,6))
方法三:
function num(min,max){
//   random取值0=<1
  return parseInt(Math.random()*(max-min))+min
}
console.log(num(1,5))
console.log(num(3,6))

2、写一个函数,返回从min都max之间的 随机整数,包括min包括max

function num(min,max){
//   random取值0=<1
  return Math.floor(Math.random()*(max-min+1))+min
}
console.log(num(1,5))
console.log(num(3,6))

3、写一个函数,生成一个长度为 n 的随机字符串,字符串字符的取值范围包括0到9,a到 z,A到Z

function getRandStr(len){
  //补全函数
}
var str = getRandStr(10); // 0a3iJiRZap
方法:
function getRandStr(length){
   //声明空字符串存放
   var str = ''
   //所有的字符串
   var dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
   for(var i = 0; i < length; i++){
     //获取索引值
     var index = Math.floor(Math.random()*dict.length)
     //空字符串+索引的值
     str += dict[index]
   }
  return str
}
var str = getRandStr(10); 
console.log(str)

4、写一个函数,生成一个随机 IP 地址,一个合法的 IP 地址为 0.0.0.0~255.255.255.255

function getRandIP(){
  //补全
}
var ip = getRandIP()
console.log(ip) // 10.234.121.45
方法一:
function getRandIP(){
  //声明数组存放ip地址
  var arr = []
  for(var i = 0;i < 4; i++){
    //随机ip数
    var num = Math.ceil(Math.random()*255)
    //遍历的值都添加到数组
    arr.push(num)
  }
  //返回用'.'连接
  return arr.join('.')
}
var ip = getRandIP()
console.log(ip) // 10.234.121.45

方法二:自己想的,不具有代表性
function getRandIP(){
  //声明字符串存放ip地址
  var str = ''
  for(var i = 0;i < 4; i++){
    //随机ip数
    var num = Math.ceil(Math.random()*255)+ `a`
    //遍历的值都添加到数组
    str += num
  }
  //返回用'.'连接并截取去掉最后一个点
  return (str.replace(/[a-z]/g,'.')).slice(0,-1)
}
var ip = getRandIP()
console.log(ip) // 10.234.121.45

5、写一个函数,生成一个随机颜色字符串,合法的颜色为#000000~ #ffffff

function getRandColor(){
}
var color = getRandColor()
console.log(color)   // #3e2f1b
function getRandColor(length){
  var str = '#'
  var dict = '0123456789abcdef'
  for(var i = 0;i < 6;i++){
    var index = Math.floor(Math.random()*dict.length)
    str += dict[index]
  }
  return str
}
var color = getRandColor()
console.log(color)   // #3e2f1b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant