用随机函数接收一个布尔类型参数,表示颜色的格式是十六进制还是rgb格式。

74 阅读1分钟
 //1.定义一个随机的函数
function getColor(flag = true) {
// 条件判断
      if (flag) {
        let sum = '#'
        let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
        //利用for 循环 循环数组 6次 累加到 sum 里面 得到 #ffffff
        for (let i = 0; i < 6; i++) {
        // random 是数组里面的索引号 每次循环都是从数组里面随机抽取一个
          let random = Math.floor(Math.random() * arr.length)
          sum += arr[random]
        }
        return sum
      } else {
        let r = Math.floor(Math.random() * 266)
        let g = Math.floor(Math.random() * 266)
        let b = Math.floor(Math.random() * 266)
        return `rgb(${r},${g},${b})`
      }
    }
    let str = getColor(true)
    document.write(`${str}<br>`)
    let str1 = getColor(false)
    document.write(`${str1}<br>`)
- | ------ |
 //调用函数
 console.log(getColor(true))
 console.log(getColor(false))