JavaScript Math 对象

JavaScript Math 对象

原文链接

Math 是 JavaScript 的一个内置的、静态的对象,它为数学常量和数学函数供应了属性和要领。

Math 是一个 Object 对象实例,所以它没有 prototype 属性。

var math = new Math(); // 报错,TypeError: Math is not a constructor(…)

Math.prototype;        // undefined

Math.__proto__;        // Object {}

Math.__proto__ === Object.prototype;    // true

一个对象的 __proto__ 属性指向组织该对象的组织函数的原型

属性

Math.E;     // 欧拉常数,也是自然对数的底数,值约为 2.718...
Math.PI;    // 圆周率,3.1415926....

这里只提这两个属性。

要领

  • 经常运用

    • Math.abs(num):返回 num 的绝对值

    • Math.pow(base, exponent):返回基数(base)的指数(exponent)次幂,即 baseexponent

    • Math.sqrt(x):返回一个数的平方根

Math.abs(-11);   // 11
Math.pow(5,2);   // 25
Math.sqrt(16);   // 4
  • 找最值

    • Math.max(num1,num2,…):返回一组数中的最大值

    • Math.min(num1,num2,…):返回一组数中的最小值

不要向上面的2个函数直接传入数字数组。

var numArray = [1,2,33,-11,33];

Math.max(numArray);   // NaN
Math.min(numArray);   // NaN

不过,我们能够如许玩:运用函数的 apply() 要领

var numArray = [1,2,33,-11,33];

Math.max.apply(Math,numArray);   // 33
Math.min.apply(Math,numArray);   // -11

假如你不清楚上面的完成道理,能够参看 这个链接(引荐去看看)

  • 舍入要领

    • Math.ceil(num):将 num 向上舍入为最接近的整数

    • Math.floor(num):将 num 向下舍入为最接近的整数

    • Math.round(num):实行规范舍入,即四舍五入

var num = 5.21;

Math.ceil(num);    // 6 
Math.floor(num);   // 5
Math.round(num);   // 5
  • 天生随机数

    • Math.random():返回一个大于即是 0 小于 1 的随机数。

// 返回一个介于min和max之间的整型随机数 [min,max]
// Using Math.round() will give you a non-uniform distribution(不均匀散布)!

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
  • 其他

    • Math.sin()

    • Math.cos()

    • Math.tan()

    • Math.log()

    • ……

    原文作者:percy507
    原文地址: https://segmentfault.com/a/1190000006799585
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞