一篇文章带你了解JavaScript math(下篇)

[[348732]]

 JavaScript的Math对象允许你对数字进行数学操作。上篇文章我们已经介绍了基本的Math函数用法,这篇文章我们来讲讲三角函数还有部分其他函数的用法。

一、三角函数
1. Math.sin()
Math.sin(x) 返回角度x的正弦值(-1到1之间)(以弧度)。

如果你想使用角度而不是弧度,你必须转换为弧度。

Angle in radians = Angle in degrees x PI / 180。

 
 
 
 
  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.   <meta charset="UTF-8"
  5.   <title>项目</title> 
  6. </head> 
  7. <body  style="background-color: aqua;"
  8.  
  9.   <h1>JavaScript Math.sin()</h1> 
  10.  
  11.   <p>Math.sin(x) 返回x的正弦值:</p> 
  12.   <p>角弧度 = (度角) * PI / 180.</p> 
  13.  
  14.   <p id="demo"></p> 
  15.  
  16.   <script> 
  17.     document.getElementById("demo").innerHTML = 
  18.     "90 度的正弦值是:" + Math.sin(90 * Math.PI / 180); 
  19. </script> 
  20.  
  21. </body> 
  22. </html> 

2. Math.cos()
Math.cos(x) 返回x的余弦值(-1到1之间)(以弧度)。

如果你想使用角度而不是弧度,你必须转换为弧度。

Angle in radians = Angle in degrees x PI / 180。

 
 
 
 
  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.   <meta charset="UTF-8"
  5.   <title>项目</title> 
  6. </head> 
  7. <body  style="background-color: aqua;"
  8.  
  9.   <h1>JavaScript Math.cos()</h1> 
  10.  
  11.   <p>Math.cos(x) 返回x的余弦值(以弧度):</p> 
  12.   <p>角弧度 = (度角) * PI / 180.</p> 
  13.  
  14.   <p id="demo"></p> 
  15.  
  16.   <script> 
  17.     document.getElementById("demo").innerHTML = 
  18.     "0度的余弦值是:" + Math.cos(0 * Math.PI / 180); 
  19. </script> 
  20.  
  21. </body> 
  22. </html> 

3. 其他函数
1. Math.min()
Math.min() 和 Math.max() 可用于在参数列表中查找最低或最高值。

 
 
 
 
  1. <script> 
  2.     document.getElementById("demo").innerHTML = 
  3.     Math.min(0, 150, 30, 20, -8, -200); // returns -200 
  4. </script> 

2. Math.max()

 
 
 
 
  1. <script> 
  2.     document.getElementById("demo").innerHTML = 
  3.     Math.max(0, 150, 30, 20, -8, -200); 
  4. </script> 

二、Math 属性 (常量)
JavaScript 提供8个可以被Math对象访问的数学常数:(来源百度)。

 
 
 
 
  1. Math.E        // returns Euler's number 
  2. Math.PI       // returns PI 
  3. Math.SQRT2    // returns the square root of 2 
  4. Math.SQRT1_2  // returns the square root of 1/2 
  5. Math.LN2      // returns the natural logarithm of 2 
  6. Math.LN10     // returns the natural logarithm of 10 
  7. Math.LOG2E    // returns base 2 logarithm of E 
  8. Math.LOG10E   // returns base 10 logarithm of E 

三、总结
本文基于JavaScript基础,讲解数学函数在实际中的应用。从最基本的函数开始,讲解Math函数中常见的方法,有三角函数方法,还有其他的一些常见的函数,都做了详细的讲解。用大量的案例进行分析,对Math函数如何去运用这些方法函数,以及在实际运用中遇到难点都做了详细讲解。

丰富效果图的展示,能够更好的理解。希望通过本文的学习 读者能够更好的学习JavaScript。

THE END