Math 相关
Math 是一个 JavaScript 内建的物件,可以让我们进行数学运算,在 console 输入 Math 这个 object 包含的内容和可用的函式。
下面我们就来看看 Math 中都有哪些可用的功能吧!
Math.PI
顾名思义,表示圆周率,当我们进行相关运算时可以直接使用 Math.PI
做计算。
Math.PI // 3.141592653589793
Math.abs()
会回传绝对值。
Math.abs(-3); // 3Math.abs(3); // 3
Math.max()、Math.min()
回传参数中最大/最小的值。
Math.max(2, 1, 4, 5, 8, -2); // 8Math.min(2, 1, 4, 5, 8, -2); // -2
Math.round
会将数字四捨五入到整数并回传,也可以使用先乘再除的技巧取到小数位数。
Math.round(5.55); // 6Math.round(5.45); // 5Math.round(2); // 2Math.round(-10.5); // -10Math.round(-10.51); // -11// 若要取到小数点第一位则可以先乘 10 再除 10Math.round(5.45*10)/10; // 5.5// 取到小数点第二位则先乘 100 再除 100Math.round(5.456*100)/100; // 5.46
Math.ceil
ceil
是天花板的意思,会将数字无条件进位到整数并回传,同样可以使用先乘后除的技巧。
Math.ceil(5.55); // 6Math.ceil(5.45); // 6Math.ceil(-4.66); // -4Math.ceil(-7.004); // -7
Math.floor
会将数字无条件捨去到整数并回传,同样可以使用先乘后除的技巧。
Math.floor(5.55); // 5Math.floor(5.45); // 5Math.floor(-5.05); // -6
Math.random
会随机回传 0 到 1 之间的小数。
Math.random(); // 产生随机小数
产生小数这个功能乍看之下好像没什么用,但实际上我们经常使用 random
产生随机乱数,那具体究竟是怎么操作的呢:
// 先来分析一下,random 会产生 0 到 1 的小数Math.random(); // 0.26143194223248645// 若我们想产生整数,可以使用 Math.floor() 去除小数Math.floor(Math.random()); // 结果都是 0,因为 random 都是 0. 开头// 因小数点第一位範围为 0 ~ 9,由此可知在,random *10 后 floor 的结果为 0 ~ 9 的随机整数Math.floor(Math.random() * 10); // 产生 0 ~ 9 随机整数// 将结果 +1 后可产生 1 ~ 10 随机整数Math.floor((Math.random() * 10 + 1)); // 产生 1 ~ 10 随机整数
由此推论,当我们要产生某两数间随机数时,公式为:
Math.floor(Math.random()*(b - a + 1))+a;// 产生 1 ~ 10Math.floot((Math.random() * (10 - 1 + 1)) + 1);
若想了解更多可以参考:MDN - Math
上一篇:[快速入门前端 56] JavaScript:Array 阵列 (3) 常见阵列操作方法
下一篇:[快速入门前端 58] JavaScript:常见的内建函式 (2) Number 和 String 相关
系列文章列表:[快速入门前端] 系列文章索引列表