Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tính lũy thừa (cơ số mũ) trong JavaScript

Dùng Math.pow(base, exponent) trả về base^exponent.

Ví dụ

<html>
  <head>
    <title>Phương thức Math.pow trong JavaScript</title>
  </head>
  <body>
    <script>
      document.write("7^2 = " + Math.pow(7, 2) + "<br>"); // 49
      document.write("8^8 = " + Math.pow(8, 8) + "<br>"); // 16777216
      document.write("(-1)^2 = " + Math.pow(-1, 2) + "<br>"); // 1
      document.write("0^10 = " + Math.pow(0, 10)); // 0
    </script>
  </body>
</html>

ES6: Có thể dùng toán tử **: 7 ** 2 (49).