JavaScript 指数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5907063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:27:15  来源:igfitidea点击:

JavaScript exponents

javascriptmath

提问by McKayla

How do you do exponents in JavaScript?

你如何在 JavaScript 中计算指数?

Like how would you do 12^2?

比如你会怎么做 12^2?

采纳答案by Salvador Dali

There is an exponentiation operator, which is part of the ES7 final specification. It is supposed to work in a similar manner with python and matlab:

有一个求幂运算符,它是 ES7 最终规范的一部分。它应该与 python 和 matlab 以类似的方式工作:

a**b // will rise a to the power b

Now it is already implemented in Edge14, Chrome52, and also it is available with traceur or babel.

现在它已经在 Edge14、Chrome52 中实现,并且它也可以与 traceur 或 babel 一起使用。

回答by Ignacio Vazquez-Abrams

Math.pow():

Math.pow()

js> Math.pow(12, 2)
144

回答by Tieson T.

Math.pow(base, exponent), for starters.

Math.pow(base, exponent), 对于初学者。

Example:

例子:

Math.pow(12, 2)

回答by Anon Ymus

Math.pow(x, y)works fine for x^y and even evaluates the expression when y is not an integer. A piece of code not relying on Math.powbut that can only evaluate integer exponents is:

Math.pow(x, y)对 x^y 工作正常,甚至在 y 不是整数时评估表达式。一段不依赖Math.pow但只能计算整数指数的代码是:

function exp(base, exponent) {
  exponent = Math.round(exponent);
  if (exponent == 0) {
    return 1;
  }
  if (exponent < 0) {
    return 1 / exp(base, -exponent);
  }
  if (exponent > 0) {
    return base * exp(base, exponent - 1)
  }
}

回答by Mayank_VK

How we perform exponents in JavaScript
According to MDN
The exponentiation operatorreturns the result of raising the first operand to the power second operand. That is, var1 var2, in the preceding statement, where var1 and var2 are variables. Exponentiation operator is right associative: a ** b ** c is equal to a ** (b ** c).
For example:
2**3// here 2 will multiply 3 times by 2 and the result will be 8.
4**4// here 4 will multiply 4 times by 4 and the result will be 256.

我们如何在 JavaScript 中执行指数
根据 MDN指数运算符返回将第一个操作数提高到第二个操作数
的结果。即 var1 var2,在前面的语句中,var1 和 var2 是变量。求幂运算符是右结合的:a ** b ** c 等于 a ** (b ** c)。
例如:
2**3// 这里 2 将乘以 2 3 次,结果为 8。
4**4// 这里 4 将 4 次乘以 4,结果为 256。