Math对象小结

194 阅读1分钟

一、min()和max()

min()方法和max()方法用来确定一组数值中最小值和最大值,这两个方法都可以接受任意数量的参数
基础用法:
    const max = Math.max(1,2,3,4,5)
    console.log(max); // 5
对于判断数组中的最大值:
    const arr = [1,2,3,4,5]
    const max = Math.max(...arr)
    console.log(max);  // 5
以上方法通过扩展运算符,变成基础用法的格式,即可得出正确的最大值,除此还有一种方法:
    const arr = [1,2,3,4,5]
    const max = Math.max.apply(Math,arr)
    console.log(max);  // 5
该方法是将Math对象作为apply的第一个参数,正确的设置 this 值,可以将数组作为第二个参数。

二、舍入方法

将小数舍入有三种方法,ceil()、round()、floor()

1、Math.ceil()

  console.log(Math.ceil(9.1));  // 10
  console.log(Math.ceil(9.5));  // 10
  console.log(Math.ceil(9.6));  // 10
  Math.ceil() 执行的是向上舍入,所以介于9 - 10 之间的任何数都会返回10

2、Math.round()

  console.log(Math.round(9.1));  // 9
  console.log(Math.round(9.5));  // 10
  console.log(Math.round(9.6));  // 10
  Math.round() 执行的就是我们数学中学到的四舍五入

3、Math.floor()

  console.log(Math.round(9.1));  // 9
  console.log(Math.round(9.5));  // 9
  console.log(Math.round(9.6));  // 9
  Math.floor() 执行的是向下舍入,所以介于9 - 10 之间的任何数都会返回9

三、随机数 Math.random()

Math.random()方法会返回大于等于0小于等于1的随机数,那当我们如果需要一定范围的随机整数呢?
Math.floor(Math.random() * num1 + num2)
该方法中,num1 代表可能值的总数,也就是范围间可能出现的随机数的数量,num2 代表范围内最小的值
例如:
Math.floor(Math.random() * 10 + 1)
就可以产生 1 - 10 之间的随机整数