javascript math 對(duì)象
javascript math 對(duì)象允許您對(duì)數(shù)字執(zhí)行數(shù)學(xué)任務(wù)。
范例
math.pi; // 返回 3.141592653589793
1. math.round()
math.round(x) 的返回值是 x 四舍五入為最接近的整數(shù):
范例
math.round(6.8); // 返回 7 math.round(2.3); // 返回 2
2. math.pow()
math.pow(x, y) 的返回值是 x 的 y 次冪:
范例
math.pow(8, 2); // 返回 64
3. math.sqrt()
math.sqrt(x) 返回 x 的平方根:
范例
math.sqrt(64); // 返回 8
4. math.abs()
math.abs(x) 返回 x 的絕對(duì)(正)值:
范例
math.abs(-4.7); // 返回 4.7
5. math.ceil()
math.ceil(x) 的返回值是 x 上舍入最接近的整數(shù):
范例
math.ceil(6.4); // 返回 7
6. math.floor()
math.floor(x) 的返回值是 x 下舍入最接近的整數(shù):
范例
math.floor(2.7); // 返回 2
7. math.sin()
math.sin(x) 返回角 x(以弧度計(jì))的正弦(介于 -1 與 1 之間的值)。
如果您希望使用角度替代弧度,則需要將角度轉(zhuǎn)換為弧度:
angle in radians = angle in degrees x pi / 180.
范例
math.sin(90 * math.pi / 180); // 返回 1(90 度的正弦)
8. math.cos()
math.cos(x) 返回角 x(以弧度計(jì))的余弦(介于 -1 與 1 之間的值)。
如果您希望使用角度替代弧度,則需要將角度轉(zhuǎn)換為弧度:
angle in radians = angle in degrees x pi / 180.
范例
math.cos(0 * math.pi / 180); // 返回 1(0 度的余弦)
9. math.min() 和 math.max()
math.min() 和 math.max() 可用于查找參數(shù)列表中的最低或最高值:
范例
math.min(0, 450, 35, 10, -8, -300, -78); // 返回 -300
范例
math.max(0, 450, 35, 10, -8, -300, -78); // 返回 450
10. math.random()
math.random() 返回介于 0(包括) 與 1(不包括) 之間的隨機(jī)數(shù):
范例
math.random(); // 返回隨機(jī)數(shù)
您將在本教程的下一章學(xué)到更多有關(guān) math.random() 的知識(shí)。
11. math 屬性(常量)
javascript 提供了可由 math 對(duì)象訪(fǎng)問(wèn)的 8 個(gè)數(shù)學(xué)常量:
范例
math.e // 返回歐拉指數(shù)(euler's number) math.pi // 返回圓周率(pi) math.sqrt2 // 返回 2 的平方根 math.sqrt1_2 // 返回 1/2 的平方根 math.ln2 // 返回 2 的自然對(duì)數(shù) math.ln10 // 返回 10 的自然對(duì)數(shù) math.log2e // 返回以 2 為底的 e 的對(duì)數(shù)(約等于 1.414) math.log10e // 返回以 10 為底的 e 的對(duì)數(shù)(約等于0.434)
12. math 構(gòu)造器
與其他全局對(duì)象不同,math對(duì)象沒(méi)有構(gòu)造函數(shù)。方法和屬性是靜態(tài)的。
可以在不首先創(chuàng)建math對(duì)象的情況下使用所有方法和屬性(常量)。
13. math 對(duì)象方法
方法 | 描述 |
---|---|
abs(x) | 返回 x 的絕對(duì)值 |
acos(x) | 返回 x 的反余弦值,以弧度計(jì) |
asin(x) | 返回 x 的反正弦值,以弧度計(jì) |
atan(x) | 以介于 -pi/2 與 pi/2 弧度之間的數(shù)值來(lái)返回 x 的反正切值。 |
atan2(y,x) | 返回從 x 軸到點(diǎn) (x,y) 的角度 |
ceil(x) | 對(duì) x 進(jìn)行上舍入 |
cos(x) | 返回 x 的余弦 |
exp(x) | 返回 ex 的值 |
floor(x) | 對(duì) x 進(jìn)行下舍入 |
log(x) | 返回 x 的自然對(duì)數(shù)(底為e) |
max(x,y,z,...,n) | 返回最高值 |
min(x,y,z,...,n) | 返回最低值 |
pow(x,y) | 返回 x 的 y 次冪 |
random() | 返回 0 ~ 1 之間的隨機(jī)數(shù) |
round(x) | 把 x 四舍五入為最接近的整數(shù) |
sin(x) | 返回 x(x 以角度計(jì))的正弦 |
sqrt(x) | 返回 x 的平方根 |
tan(x) | 返回角的正切 |