Math.random 生成随机数

首先是 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));

猜你喜欢

转载自www.cnblogs.com/doumian/p/12657213.html