JavaScript BigInt BigInt() 構造函數用於將任何原始數據類型或對象轉換為 BigInt 數據類型。它返回一個新的 BigInt 對象,表示原始值。當處理超過安全整數限製 9007199254740991 的大數時,此方法特別有用。
用法:
BigInt(value);
Parameters: BigInt() 構造函數采用一個參數,該參數是需要轉換為 BigInt 數據類型的值。
Note:此參數可以是基本數據類型,例如數字、字符串或布爾值,也可以是對象。
返回值:BigInt() 構造函數返回一個新的 BigInt 對象,該對象表示作為參數傳遞的原始值。
示例 1: 斐波那契數列與 BigInt:在此示例中,我們將創建一個函數來使用 BigInt 生成達到給定索引的斐波那契序列。我們將使用BigInt.bigInt()當斐波那契數列快速增長並超過最大安全整數大小時,將數字轉換為 BigInt 的方法。
Javascript
// This function calculates the
// Fibonacci sequence up to a
// given number 'n'
function fibonacci(n) {
let sequence = [0n, 1n];
for (let i = 2; i <= n; i++) {
sequence[i] = BigInt(sequence[i - 1])
+ BigInt(sequence[i - 2]);
}
return sequence;
}
console.log(fibonacci(10));
[ 0n, 1n, 1n, 2n, 3n, 5n, 8n, 13n, 21n, 34n, 55n ]
示例 2: 使用 BigInt 計算大階乘:在此示例中,我們將創建一個函數來使用 BigInt 計算大數的階乘。我們將使用 BigInt.bigInt() 方法將數字轉換為 BigInt,因為階乘可能非常大。
Javascript
// This function calculates the
// Factorial of given number 'n'
function factorial(n) {
let result = 1n;
for (let i = 2n; i <= n; i++) {
result *= BigInt(i);
}
return result;
}
console.log(factorial(30));
265252859812191058636308480000000n
示例 3: 使用 BigInt 進行大數求冪:在此示例中,我們將創建一個函數來計算大數的大冪的值。我們將使用 BigInt.bigInt() 方法將數字轉換為 BigInt,因為底數和指數都可能非常大。
Javascript
// This function calculates the Power
// of given base and exponent
function power(base, exponent) {
let result = 1n;
for (let i = 0n; i < exponent; i++) {
result *= BigInt(base);
}
return result;
}
console.log(power("123456789", 10));
822526259147102579504761143661535547764137892295514168093701699676416207799736601n
支持的瀏覽器:
- chrome 67.0
- 邊 79.0
- 火狐瀏覽器68.0
- Opera 54.0
- Safari 14.0
相關用法
- JavaScript BigInt.prototype.toLocaleString()用法及代碼示例
- JavaScript BigInt.prototype.toString()用法及代碼示例
- JavaScript BigInt.prototype.valueOf()用法及代碼示例
- JavaScript BigInt toString()用法及代碼示例
- JavaScript BigInt toLocaleString()用法及代碼示例
- JavaScript BigInt valueOf()用法及代碼示例
- JavaScript Boolean constructor()用法及代碼示例
- JavaScript Boolean toSource()用法及代碼示例
- JavaScript Boolean toString()用法及代碼示例
- JavaScript Boolean valueOf()用法及代碼示例
- JavaScript Boolean()用法及代碼示例
- JavaScript Math cosh()用法及代碼示例
- JavaScript Math sinh()用法及代碼示例
- JavaScript Math sin()用法及代碼示例
- JavaScript Math cos()用法及代碼示例
- JavaScript Math tan()用法及代碼示例
- JavaScript Math abs()用法及代碼示例
- JavaScript Math pow()用法及代碼示例
- JavaScript Math asin()用法及代碼示例
- JavaScript Math acos()用法及代碼示例
- JavaScript Math atan()用法及代碼示例
- JavaScript Math ceil()用法及代碼示例
- JavaScript Math floor()用法及代碼示例
- JavaScript Math round()用法及代碼示例
- JavaScript Math trunc()用法及代碼示例
注:本文由純淨天空篩選整理自gangiswathi2000大神的英文原創作品 JavaScript BigInt() Constructor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。