Math是JS的内置对象,提供一系列数学常数和数学方法。该对象不是构造函数,不能生成实例,所有的属性和方法都必须在Math对象上调用。
new Math()
// TypeError: object is not a function
上面代码表示,Math
不能当作构造函数用。
一、属性
Math
对象提供以下一些只读的数学常数。(知道这么回事就好,没用过)
二、方法
Math
对象提供以下一些常用的数学方法。
Math.max():最大值
Math.min():最小值
Math.floor():向下取整
Math.ceil():向上取整
Math.round():四舍五入
Math.random():随机数
-
Math.max
方法和Math.min
方法都可以接受多个参数,Math.max
返回其中最大的参数,Math.min
返回最小的参数。
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
-
Math.floor
方法接受一个参数,返回小于该参数的最大整数。
Math.floor(3.2) // 3
Math.floor(-3.2) // -4
-
Math.ceil
方法接受一个参数,返回大于该参数的最小整数。
Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3
如果需要总是返回某个数值整数部分的函数,可以自己实现:
function ToInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
上面代码中,不管正数或负数,ToInteger
函数总是返回一个数值的整数部分。
-
Math.round
方法用于四舍五入。
Math.round(0.1) // 0
Math.round(0.5) // 1
Math.round(0.6) // 1
注意,它对负数的处理,主要是对0.5的处理。
Math.round(-1.1) // -1
Math.round(-1.5) // -1
Math.round(-1.6) // -2
2.1、Math.random()
这个是Math
对象中最灵活也是最常用最重要的方法了。
该方法返回0到1之间的一个伪随机数(计算机没有随机数,都是确定的数),可能等于0,但是一定小于1。
- 任意给定范围的随机数生成函数:
function getRandom(min, max){
return Math.random()*(max-min)+min;
}
- 任意给定范围的随机整数生成函数:
function getRandom(min, max){
return Math.floor( Math.random()*(max-min+1)+min );
}
- 返回随机字符:
function random_str(length) {
var ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
ALPHABET += 'abcdefghijklmnopqrstuvwxyz';
ALPHABET += '0123456789-_';
var str = '';
for (var i=0; i < length; ++i) {
var rand = Math.floor(Math.random() * ALPHABET.length);
str += ALPHABET.substring(rand, rand + 1);
}
return str;
}
random_str(6) // "NdQKOr"
上面代码中,random_str
函数接受一个整数作为参数,返回变量ALPHABET
内的随机字符所组成的指定长度的字符串。
2.2、三角函数方法
Math
对象还提供一系列三角函数方法。
Math.sin():返回参数的正弦
Math.cos():返回参数的余弦
Math.tan():返回参数的正切
Math.asin():返回参数的反正弦(弧度值)
Math.acos():返回参数的反余弦(弧度值)
Math.atan():返回参数的反正切(弧度值)
(本系列下一节为 — JSON对象)
网友评论