一篇文章帶你了解JavaScript math(下篇)
JavaScript的Math對象允許你對數(shù)字進(jìn)行數(shù)學(xué)操作。上篇文章我們已經(jīng)介紹了基本的Math函數(shù)用法,這篇文章我們來講講三角函數(shù)還有部分其他函數(shù)的用法。
一、三角函數(shù)
1. Math.sin()
Math.sin(x) 返回角度x的正弦值(-1到1之間)(以弧度)。
如果你想使用角度而不是弧度,你必須轉(zhuǎn)換為弧度。
Angle in radians = Angle in degrees x PI / 180。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>項目</title>
- </head>
- <body style="background-color: aqua;">
- <h1>JavaScript Math.sin()</h1>
- <p>Math.sin(x) 返回x的正弦值:</p>
- <p>角弧度 = (度角) * PI / 180.</p>
- <p id="demo"></p>
- <script>
- document.getElementById("demo").innerHTML =
- "90 度的正弦值是:" + Math.sin(90 * Math.PI / 180);
- </script>
- </body>
- </html>
2. Math.cos()
Math.cos(x) 返回x的余弦值(-1到1之間)(以弧度)。
如果你想使用角度而不是弧度,你必須轉(zhuǎn)換為弧度。
Angle in radians = Angle in degrees x PI / 180。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>項目</title>
- </head>
- <body style="background-color: aqua;">
- <h1>JavaScript Math.cos()</h1>
- <p>Math.cos(x) 返回x的余弦值(以弧度):</p>
- <p>角弧度 = (度角) * PI / 180.</p>
- <p id="demo"></p>
- <script>
- document.getElementById("demo").innerHTML =
- "0度的余弦值是:" + Math.cos(0 * Math.PI / 180);
- </script>
- </body>
- </html>
3. 其他函數(shù)
1. Math.min()
Math.min() 和 Math.max() 可用于在參數(shù)列表中查找最低或最高值。
- <script>
- document.getElementById("demo").innerHTML =
- Math.min(0, 150, 30, 20, -8, -200); // returns -200
- </script>
2. Math.max()
- <script>
- document.getElementById("demo").innerHTML =
- Math.max(0, 150, 30, 20, -8, -200);
- </script>
二、Math 屬性 (常量)
JavaScript 提供8個可以被Math對象訪問的數(shù)學(xué)常數(shù):(來源百度)。
- Math.E // returns Euler's number
- Math.PI // returns PI
- Math.SQRT2 // returns the square root of 2
- Math.SQRT1_2 // returns the square root of 1/2
- Math.LN2 // returns the natural logarithm of 2
- Math.LN10 // returns the natural logarithm of 10
- Math.LOG2E // returns base 2 logarithm of E
- Math.LOG10E // returns base 10 logarithm of E
三、總結(jié)
本文基于JavaScript基礎(chǔ),講解數(shù)學(xué)函數(shù)在實際中的應(yīng)用。從最基本的函數(shù)開始,講解Math函數(shù)中常見的方法,有三角函數(shù)方法,還有其他的一些常見的函數(shù),都做了詳細(xì)的講解。用大量的案例進(jìn)行分析,對Math函數(shù)如何去運(yùn)用這些方法函數(shù),以及在實際運(yùn)用中遇到難點都做了詳細(xì)講解。
豐富效果圖的展示,能夠更好的理解。希望通過本文的學(xué)習(xí) 讀者能夠更好的學(xué)習(xí)JavaScript。