💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# JavaScript Math(算数)对象 **Math(算数)对象的作用是:执行常见的算数任务。** ## 实例 [round()](/tiy/t.asp?f=jsrf_math_round) 如何使用 round()。 ``` <html> <body> <script type="text/javascript"> document.write(Math.round(0.60) + "<br />") document.write(Math.round(0.50) + "<br />") document.write(Math.round(0.49) + "<br />") document.write(Math.round(-4.40) + "<br />") document.write(Math.round(-4.60)) </script> </body> </html> ``` [random()](/tiy/t.asp?f=jsrf_math_random) 如何使用 random() 来返回 0 到 1 之间的随机数。 ``` <html> <body> <script type="text/javascript"> document.write(Math.random()) </script> </body> </html> ``` [max()](/tiy/t.asp?f=jsrf_math_max) 如何使用 max() 来返回两个给定的数中的较大的数。(在 ECMASCript v3 之前,该方法只有两个参数。) ``` <html> <body> <script type="text/javascript"> document.write(Math.max(5,7) + "<br />") document.write(Math.max(-3,5) + "<br />") document.write(Math.max(-3,-5) + "<br />") document.write(Math.max(7.25,7.30)) </script> </body> </html> ``` [min()](/tiy/t.asp?f=jsrf_math_min) 如何使用 min() 来返回两个给定的数中的较小的数。(在 ECMASCript v3 之前,该方法只有两个参数。) ``` <html> <body> <script type="text/javascript"> document.write(Math.min(5,7) + "<br />") document.write(Math.min(-3,5) + "<br />") document.write(Math.min(-3,-5) + "<br />") document.write(Math.min(7.25,7.30)) </script> </body> </html> ``` ## 完整的 Math 对象参考手册 我们提供 [JavaScript Math 对象的参考手册](/jsref/jsref_obj_math.asp),其中包括所有可用于算术对象的属性和方法。 该手册包含了对每个属性和方法的详细描述以及相关实例。 ## Math 对象 Math(算数)对象的作用是:执行普通的算数任务。 Math 对象提供多种算数值类型和函数。无需在使用这个对象之前对它进行定义。 ## 算数值 JavaScript 提供 8 种可被 Math 对象访问的算数值: * 常数 * 圆周率 * 2 的平方根 * 1/2 的平方根 * 2 的自然对数 * 10 的自然对数 * 以 2 为底的 e 的对数 * 以 10 为底的 e 的对数 这是在 Javascript 中使用这些值的方法:(与上面的算数值一一对应) * Math.E * Math.PI * Math.SQRT2 * Math.SQRT1_2 * Math.LN2 * Math.LN10 * Math.LOG2E * Math.LOG10E ## 算数方法 除了可被 Math 对象访问的算数值以外,还有几个函数(方法)可以使用。 ### 函数(方法)实例: 下面的例子使用了 Math 对象的 round 方法对一个数进行四舍五入。 ``` document.write(`Math.round(4.7)`) ``` 上面的代码输出为: ``` 5 ``` 下面的例子使用了 Math 对象的 random() 方法来返回一个介于 0 和 1 之间的随机数: ``` document.write(`Math.random()`) ``` 上面的代码输出为: ``` 0.9370844220218102 ``` 下面的例子使用了 Math 对象的 floor() 方法和 random() 来返回一个介于 0 和 10 之间的随机数: ``` document.write(`Math.floor(Math.random()*11)`) ``` 上面的代码输出为: ``` 3 ```