随机数的相关应用-随机颜色

347 阅读1分钟

前言: 今天来聊一聊随机数的一些小应用,首先来看看随机数本身.

随机数
  • 在JavaScript中,随机数是一个内置对象-可以生成任意范围内的随机函数

  • Math.random() 随机函数的返回值是0-1之间的一个数字,包括0但不包括1

  • 在此基础上可以生成更大的随机数,生成N-M之间的随机数. 取整可以用Math.floor()也可以用parseInt()

    Math.floor(Math.random() * (M - N + 1)) + N
    parseInt(Math.random() * (M - N + 1)) + N
    

    先来一个小demo,输出0-20之间的随机数

    let random = function (N, M) {
      return Math.floor(Math.random() * (M - N + 1) + N)
    }
    console.log(random(0, 20))

随机数-随机点名
  1. 先声明一个数组
  2. 然后用随机数获取随机数组下标
  3. 打印出数组元素
  4. 删除已经打印的数组元素
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let arr = ['刘备', '关羽', '张飞', '曹操', '马超']
    random = Math.floor(Math.random() * arr.length)
    document.write(arr[random])
    arr.splice(random, 1)
    console.log(arr)
  </script>
</body>

</html>

image.png

image.png

随机数-猜大小
  1. 生成0-100之间的随机数
  2. for循环让用户猜3次
  3. 3次结束或者用户猜对退出循环
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let flag = true
    for (let i = 0; i < 3; i++) {
      let num = +prompt('请输入0-100之间的一个整数')
      let random = Math.floor(Math.random() * 101)
      if (num > random) {
        alert('恭喜您猜大了')
      } else if (num < random) {
        alert('恭喜您猜小了')
      } else {
        flag = false
        alert('可恶,居然猜对了')
        break
      }
    }
    if (flag === true) {
      alert('您的次数已用尽')
    }
  </script>
</body>

</html>

随机数-随机颜色
  1. 输入true或者不输入参数是随机rgb
  2. 输入false是十六进制颜色
  3. rgb生成三个随机数
  4. 十六进制利用for循环6次生成6个随机数后字符串拼接
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function getColor(flag = true) {

      if (flag === true) {
        let arr = ['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++) {
          let random = Math.floor(Math.random() * arr.length)
          str += arr[random]
        }
        return str
      } else {
        let r = Math.floor(Math.random() * 256)
        let g = Math.floor(Math.random() * 256)
        let b = Math.floor(Math.random() * 256)
        return `rgb(${r},${g},${b})`
      }
    }
    let color = getColor()
    console.log(color)
    color = getColor(false)
    console.log(color)
  </script>
</body>

</html>

image.png