迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 对数字求平方

作者:迹忆客 最近更新:2024/03/17 浏览次数:

本文将说明如何以多种方式在 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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便