非常教程

JavaScript参考手册

Math

Math.log

Math.log() 函数返回一个数的自然对数,即:

∀x>0,Math.log(x)=ln(x)=the uniqueysuch thatey=x\forall x > 0, \mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique} \; y \; \text{such that} \; e^y = x

JavaScript Math.log()函数等同于数学中的ln(x)

语法

Math.log(x)

参数

x一个数字.

返回值

给定数字e的自然对数(基数)。如果数字是负数,则返回NaN

描述

如果指定的 number 为负数,则返回值为 NaN

由于 log 是 Math 的静态方法,所以应该像这样使用:Math.log(),而不是作为你创建的 Math 对象的方法。

如果您需要2或10的自然对数,请使用常量Math.LN2Math.LN10。如果您需要以2或10为底数的对数,请使用Math.log2()Math.log10()。如果您需要以其他基数为底的对数,请使用Math.log(x)/ Math.log(otherBase),如下例所示; 你可能要预先计算1 / Math.log(otherBase)。

示例

使用Math.log()

Math.log(-1); // NaN, out of range
Math.log(0);  // -Infinity
Math.log(1);  // 0
Math.log(10); // 2.302585092994046

基于不同的底数使用Math.log

下面的函数返回以 x 为底 y 的对数(即logxy):

function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

如果你运行 getBaseLog(10, 1000),则会返回2.9999999999999996,非常接近实际答案:3,原因是浮点数精度问题。

规范

Specification

Status

Comment

ECMAScript 1st Edition (ECMA-262)

Standard

Initial definition. Implemented in JavaScript 1.0.

ECMAScript 5.1 (ECMA-262)The definition of 'Math.log' in that specification.

Standard

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Math.log' in that specification.

Standard

ECMAScript Latest Draft (ECMA-262)The definition of 'Math.log' in that specification.

Draft

浏览器兼容性

Feature

Chrome

Firefox

Edge

Internet Explorer

Opera

Safari

Basic Support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络