一文学习JavaScript中的数学对象Math
七娃博客26人阅读
js中数学计算的方法有很多,不去静下心来学习的话,还是不能完全了解这个对象和其方法。最近的学习Math的方法就是开发实战一个计算器。将大部分计算方法都可以学习一遍。七娃近期也有这样一个计算器造轮子的计划。
下面更新一下遇到的Math方法,遇到一个记录完善一次,加深记忆。
Math 对象
用于执行数学任务,用于执行数学任务,不能new实例化,和js其他对象不太一样
以下为Math属性:
1. Math.E - 自然对数的底数
Math.E 属性表示自然对数的底数(或称为基数),e,约等于 2.718
console.log(Math.E) //2.718281828459045
2.Math.PI - π
Math.PI 圆的周长与直径的比例,约为 3.14159
console.log(Math.PI) //3.14159
同类型属性还有以下:
Math.LN2 - 2的自然对数 ≈ 0.6931471805599453
Math.LN10 - 10的自然对数 ≈ 2.302585092994046
Math.LOG10E - 以 10 为底数,e 的对数 ≈ 0.4342944819032518
Math.SQRT1_2 - 1/2 的平方根 ≈ 0.7071067811865476
Math.SQRT2 - 2 的平方根 ≈ 1.4142135623730951
以下为Math方法:
1.Math.floor(n) -向下取整
Math.floor - 返回小于等于n的整数部分,正数部分同取整效果,负数部分按照接近n的负正数
console.log(Math.floor(1.8)) // 1 console.log(Math.floor(-1.8)) // -2
2.Math.ceil(n) -向上取整
Math.ceil - 返回大于或等于n的最小整数,向上取整
console.log(Math.ceil(1.8)) // 2 console.log(Math.ceil(-1.8)) // -1
3.Math.random() -生成随机数
Math.random - 一个浮点型伪随机数字,在0(包括 0)和1(不包括)之间。
console.log(Math.random()) // 0.6675358048184656
4.Math.min(a,b,c) -最小值
Math.min() 返回作为输入参数的数字中最小的一个,如果任一参数不能转换为数值,则返回 NaN。如果没有提供参数,返回 Infinity
console.log(Math.min(1,2,5,4)) //1 console.log(Math.min(...[1,2,5,4])) //1
5.Math.max(a,b,c) -最大值
Math.max() 返回作为输入参数的数字中最大的一个,如果任一参数不能转换为数值,则返回 NaN。如果没有提供参数,返回 Infinity
console.log(Math.max(1,2,5,4)) //5 console.log(Math.max(...[1,2,5,4])) //5
6.Math.round() -四舍五入(不准确,金融金额请不要用!!!)
Math.round() - 返回一个数字四舍五入后最接近的整数。缺点:不能精确到小数点后面的四舍五入
console.log(Math.round(3.005)) //3 console.log(Math.round(3.8)) //4
7.Math.sign(n) - 判断正负数
Math.sign() - 返回一个数字的符号,指示数字是正数,负数还是零.此函数共有 5 种返回值,分别是 1, -1, 0, -0, NaN. 代表的各是正数,负数,正零,负零,NaN。
console.log(Math.sign(3)) //1 console.log(Math.sign(-2)) //-1 console.log(Math.sign(0)) // 0 console.log(Math.sign("-5")) //-1 console.log(Math.sign(" ")) //0 console.log(Math.sign(" SSS222 ")) //NaN
8.Math.trunc() - 取整(不四舍五入)
Math.trunc() - 将数字的小数部分去掉,只保留整数部分
console.log(Math.trunc(0.123)) //0 console.log(Math.trunc(2.84)) //2 console.log(Math.trunc("foo")) //NaN
还有以下三角函数的公式:
Math.sin(x) —— 正弦值
Math.asin() —— 反正弦值
Math.sinh(x) —— 双曲正弦值
Math.asinh() —— 反双曲正弦值
Math.tan() —— 正切值
Math.atan() —— 反正切
Math.tanh() —— 双曲正切函数值
Math.cos() —— 余弦值
Math.acos() —— 反余弦值
Math.cosh() —— 双曲余弦函数
Math.acosh() —— 反双曲余弦值
Math.abs() —— 绝对值
Math.log() —— 自然对数
Math.log2() —— 数字以 2为底的对数
Math.log10() —— 以 10 为底的对数
Math.sqrt() —— 平方根
Math.hypot() —— 平方和的平方根
Math.pow() —— 指数次幂
Math.log1p() —— 数字加 1 后的自然对数 (底为 E)
评论 | 0 条评论
登录之后才可留言,前往登录