在 JavaScript 对数字求平方
    
    
            Moataz Farid
    2023年10月12日
    
    JavaScript
    JavaScript Math
    
- 
          
            在 JavaScript 中使用 
Math.pow()方法对数字求平方 - 
          
            在 JavaScript ECMAScript 6 中使用 
Exponentiation方法对数字求平方 - 
          
            在 JavaScript 中使用 
bigInt()库对数字进行平方计算 
本文将说明如何以多种方式在 JavaScript 中对数字求平方。
在 JavaScript 中使用 Math.pow() 方法对数字求平方
    
在 JavaScript 中对一个数字进行平方的一种方法是使用 Math 库中的 pow() 方法。该函数需要两个参数:第一个是我们的目标变量或值,第二个是我们想要将其乘以自身的次数。如果我们想让这个数字平方,我们将发送 2 作为第二个参数。
let squaredNumber = Math.pow(5, 2);
console.log('5*5 = ', squaredNumber);
let variable = 5;
let squaredNumber2 = Math.pow(variable, 2);
console.log('5*5 = ', squaredNumber2);
输出:
5*5 =  25
5*5 =  25
在 JavaScript ECMAScript 6 中使用 Exponentiation 方法对数字求平方
另一种在 JavaScript ECMAScript 6 中对一个数字进行平方的方法是使用 Exponentiation 方法。a ** b 方法返回的结果与 Math.pow 函数相同。用 ES6 的 Exponentiation 方法对一个数字进行平方,我们的公式是 a ** 2。
function squareMyNumber(no) {
  return no ** 2
}
let squared = squareMyNumber(5);
console.log(' 5 ** 2 = ', squared);
输出:
 5 ** 2 =  25
在 JavaScript 中使用 bigInt() 库对数字进行平方计算
最后我们要在他的教程中讲解的是如何使用 BigInteger.js 库在 JavaScript 中对一个数字进行平方运算。我们需要导入 CDN 库,如下图。
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>
然后,我们可以像这样使用它:
function squareMyNumber(no) {
  return bigInt(no).square()
}
let squared = squareMyNumber(5);
console.log('square of 5 using bigInt library= ' + squared);
输出:
26593302.js:13 square of 5 using bigInt library= 25
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe