提示
本文主要介绍 JavaScript 数学对象的使用。@ermo
# 数学对象
js 中的数学对象主要分为2个部分,常用属性和常用方法。数学对象的在 js 中的单词为 Math
。
# 常用属性
常用属性的使用语法为
var 变量名 = Math.属性名
属性 | 作用 |
---|---|
Math.PI | π |
Math.LN2 | 2的自然对数 |
Math.LN10 | 10的自然对数 |
Math.LOG2E | 以2为底的 e 的对数 |
Math.LOG10E | 以10为底的 e 的对数 |
Math.SQRT2 | 2的平方根 |
Math.SQRT1_2 | 2的平方根的倒数 |
console.log(Math.PI); // 圆周率
console.log(Math.LN2); // 2的自然对数
console.log(Math.LN10); // 10的自然对数
console.log(Math.LOG2E); // 以2为底的 e 的对数
console.log(Math.LOG10E); // 以10为底的 e 的对数
console.log(Math.SQRT2); // 2的平方根
console.log(Math.SQRT1_2); // 2的平方根的倒数
输出
PI=3.141592653589793
LN2=0.6931471805599453
LN10=2.302585092994046
LOG2E=1.4426950408889634
LOG10E=0.4342944819032518
SQRT2=1.4142135623730951
SQRT1_2=0.7071067811865476
# 常用方法
数学对象的常用方法的语法为
var 变量名 = Math.方法名(参数1, 参数2, ..., 参数n);
方法名 | 作用 |
---|---|
Math.max(arg1,arg2,...,argn) | 获取最大值 |
Math.min(arg1,arg2,...,argn) | 获取最大值 |
Math.sin() | 正弦 |
Math.cos() | 余弦 |
Math.asin() | 反正弦 |
Math.acos() | 反余弦 |
Math.atan() | 正切 |
Math.atan2() | 反正切 |
Math.floor() | 向下取整 |
Math.ceil() | 向上取整 |
Math.random() | 生成随机数 |
简单示例
// 常用方法
console.log(Math.max(1, 2, 3, 4, 5, 6)); // 取最大值
console.log(Math.min(1, 2, 3, 4, 5, 6)); // 取最小值
// sin 30度
console.log("sin30=" + Math.sin(30 * Math.PI/180)); // 正弦
// cos 60度
console.log("cos60=" + Math.cos(60 * Math.PI/180)); // 余弦
console.log(Math.asin(1)); // 反正弦
console.log(Math.acos(1)); // 反余弦
// tan 45度
console.log("tan45=" + Math.atan(45 * Math.PI/180)); // 正切
console.log(Math.atan(1)); // 反正切
console.log(Math.atan2(2)); // 反正切
console.log(Math.floor(2.1234)); // 向下取整
console.log(Math.ceil(2.1234)); // 向上取整
console.log(Math.random()); // 生成随机数
// 生成0~m随机数,生成随机数的范围 [0,m) 左闭右开
console.log("生成0~10随机数=" + Math.random() * 10); // 生成0~10随机数
// 生成n~m+n随机数
var random = Math.random() * 8 + 10;
console.log("生成10~18随机数=" + random); // 生成10~18随机数
// 生成-n~m-n随机数
var random1 = Math.random() * 6 - 2; // 生成-2~4随机数
console.log("生成-2~4随机数=" + random1);
// 生成-m~m随机数
var random3 = Math.random() * 6 - 6;
console.log("生成-6~6随机数=" + random3); // 生成-6~6随机数
function genRandomInt(m) {
return Math.floor(Math.random() * (m + 1));
}
// 生成0~m随机整数
console.log("生成0~5随机整数=" + genRandomInt(5)); // 生成0~5随机整数
function genRandomIntBetween(m, n) {
return Math.floor(Math.random() * (m-n+1) + n);
}
// 生成m~n随机整数
console.log("生成10~15随机整数=" + genRandomIntBetween(10, 15)); // 生成10~15随机整数