概述
Math.log() 函数返回一个数的自然对数,即:
语法
Math.log(x)
参数
-
x - 一个数字.
描述
如果指定的 number 为负数,则返回值为 NaN。
由于 log 是 Math 的静态方法,所以应该像这样使用:Math.log(),而不是作为你创建的 Math 对象的方法。
示例
例子1:使用Math.log
下面的函数返回指定变量的自然对数:
Math.log(-1); // NaN, out of range Math.log(0); // -Infinity Math.log(1); // 0 Math.log(10); // 2.302585092994046
例子2: 使用Math.log时基于不同的底数
下面的函数返回以 x 为底 y 的对数(即logx y):
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
如果你运行 getBaseLog(10, 1000),则会返回2.9999999999999996,非常接近实际答案:3,原因是浮点数精度问题。
规范
| 规范版本 | 规范状态 | 注解 |
|---|---|---|
| ECMAScript 1st Edition. Implemented in JavaScript 1.0 | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) Math.log |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) Math.log |
Standard |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains.
Find out how you can help!
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
相关链接
- The
Mathobject it belongs to. Math.exp()Math.pow()