1、Math 对象的属性
// 自然对数的底数,常量e的值
document.write(Math.E); // 2.718281828459045
// 10的自然对数
document.write(Math.LN10); // 2.302585092994046
// 2的自然对数
document.write(Math.LN2); // 0.6931471805599453
// 以10为底e的对数
document.write(Math.LOG10E); // 0.4342944819032518
// 以2为底e的对数
document.write(Math.LOG2E); // 1.4426950408889634
// π的值
document.write(Math.PI); // 3.141592653589793
// 1/2的平方根
document.write(Math.SQRT1_2); //0.7071067811865476
// 2的平方根
document.write(Math.SQRT2); //1.4142135623730951
2、min()和 max()方法用于确定一组数值中的最小值和最大值。这两个方法都可以接收任意多个数值参数。
var max = Math.max(16, 56, 38, 10);
document.write(max); // 56
var min = Math.min(16, 56, 38, 10);
document.write(min); // 10
要找到数组中的最大或最小值,可以像下面这样使用 apply()方法。
var values = [1, 3, 5, 7, 9, 11];
// 把Math对象作为apply()的第一个参数,从而正确地设置this值
var max = Math.max.apply(Math, values);
document.write(max); // 11
3、舍入方法
Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数。
// ceil向上取整
document.write(Math.ceil(3.2)); // 4
document.write(Math.ceil(3.9)); // 4
document.write(Math.ceil(3.5)); // 4
// floor向下取整
document.write(Math.floor(3.2)); // 3
document.write(Math.floor(3.5)); // 3
document.write(Math.floor(3.9)); // 3
// round四舍五入
document.write(Math.round(3.2)); // 3
document.write(Math.round(3.5)); // 4
document.write(Math.round(3.9)); // 4
4、random()方法
Math.random()方法返回大于等于 0 小于 1 的一个随机数。
利用 Math.random() 从某个整数范围内随机选择一个值。 公式:值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值)
// 2-10之间的值
var num = Math.floor(Math.random() * 9 + 2);
document.write(num); // 7
一