首页 > 其他分享 >[JS零碎知识点01]Math内置对象

[JS零碎知识点01]Math内置对象

时间:2024-05-31 13:59:14浏览次数:17  
标签:知识点 01 floor random JS num let alert Math

一:Math数学对象

Math 是一个内置对象,它拥有一些数学常数属性和数学函数方法。

二:random()方法

1 random()简介

Math.random()为随机数函数,返回一个0到1之间随机小数数,并且包括0不包括1,[0,1)

2 随机数生成算法

(1)生成0-10之间的随机整数

Math.floor(Math.random()*11)

推倒:

Math.random(),生成数范围[0,1)

Math.random()*11,生成数范围[0,11)

Math.floor(Math.random()*11),向下取整,因为取不到11,因此可以回生成0-10之间的随机数

(2)生成5-10之间的随机整数

Math.floor(Math.random()*6)+5

(3)生成N-M之间的随机数

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

3 案例

(1)需求1:

    let arr = ['赵云', '黄忠', '关羽', '张飞'],随机生成一个人的名字

let arr = ['赵云', '黄忠', '关羽', '张飞']
    let num = Math.floor(Math.random() * arr.length)
    // console.log(num);
document.write(arr[num])

(2)需求2:

程序随机生成1-10之间的一个数字,用户输入一个数字

  • 大于该数字,提示大了,继续猜
  • 小于该数字,提示小了,继续猜
  • 如果猜对了,就提示猜对了,程序结束
function getRandom(M, N) {
      return Math.floor(Math.random() * (M - N + 1)) + N
    }
    let num = getRandom(1, 10)
    console.log(num);
    while (true) {
      let guess = +prompt('请你输入一个数字')
      if (num > guess) {
        alert('你数字猜小了,请继续猜')
      } else if (num < guess) {
        alert('你数字猜大了,请继续猜')
      } else {
        alert('恭喜你,猜对了')
        break
      }
    }

添加了猜测次数版本:

// 改进版添加了限定猜数次数
    let flag = true//重点
    function getRandom(M, N) {
      return Math.floor(Math.random() * (M - N + 1)) + N
    }
    let num = getRandom(1, 10)
    for (let i = 1; i <= 3; i++) {
      let guess = +prompt('请你输入一个数字')
      if (num > guess) {
        alert('你数字猜小了,请继续猜')
      } else if (num < guess) {
        alert('你数字猜大了,请继续猜')
      } else {
        flag = false
        alert('恭喜你,猜对了')
        break
      }
    }
    if (flag) {
      alert('你的次数已用完')
    }

标签:知识点,01,floor,random,JS,num,let,alert,Math
From: https://blog.csdn.net/qq_67896626/article/details/139329832

相关文章