BigInt.asIntN()

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上使用。自 2020 年 9 月起,所有瀏覽器均已提供此功能。

BigInt.asIntN() 靜態方法會將 BigInt 值截斷為指定的最低有效位元數,並以帶符號整數的形式返回該值。

試一試

const I64_CEIL = 2n ** 63n;

console.log(BigInt.asIntN(64, I64_CEIL - 1n));
// 9223372036854775807n (2n ** 64n - 1n, the maximum non-wrapping value)
console.log(BigInt.asIntN(64, I64_CEIL));
// -9223372036854775808n (wraps to min value)
console.log(BigInt.asIntN(64, I64_CEIL + 1n));
// -9223372036854775807n (min value + 1n)
console.log(BigInt.asIntN(64, I64_CEIL * 2n));
// 0n (wrapped around to zero)
console.log(BigInt.asIntN(64, -I64_CEIL * -42n));
// 0n (also wraps on negative multiples)

語法

js
BigInt.asIntN(bits, bigint)

引數

bits

返回的 BigInt 可用的位元數。應為介於 0 和 253 - 1 之間(包含)的整數。

bigint

要截斷以適應所提供位元數的 BigInt 值。

返回值

bigint2 ** bits 取模後的值,以帶符號整數形式表示。

異常

RangeError

如果 bits 為負數或大於 253 - 1,則丟擲此錯誤。

描述

BigInt.asIntN 方法會將 BigInt 值截斷為指定的位元數,並將結果解釋為帶符號整數。例如,對於 BigInt.asIntN(3, 25n),值 25n 被截斷為 1n

25n = 00011001 (base 2)
          ^=== Use only the three remaining bits
===>       001 (base 2) = 1n

如果剩餘數字的最高有效位元是 1,則結果為負數。例如,BigInt.asIntN(4, 25n) 得到 -7n,因為在二進位制補碼錶示中,1001-7 的編碼。

25n = 00011001 (base 2)
         ^==== Use only the four remaining bits
===>      1001 (base 2) = -7n

注意: BigInt 值在二進位制中始終編碼為二進位制補碼。

與諸如 Number.prototype.toExponential() 等類似的語言 API 不同,asIntNBigInt 的一個靜態屬性,因此您始終將其用作 BigInt.asIntN(),而不是作為 BigInt 值的某個方法。將 asIntN() 作為“標準庫函式”暴露出來,可以實現與 asm.js 的互操作

示例

保持在 64 位範圍內

BigInt.asIntN() 方法有助於保持在 64 位算術範圍內。

js
const max = 2n ** (64n - 1n) - 1n;

BigInt.asIntN(64, max); // 9223372036854775807n

BigInt.asIntN(64, max + 1n); // -9223372036854775808n
// negative because the 64th bit of 2^63 is 1

規範

規範
ECMAScript® 2026 語言規範
# sec-bigint.asintn

瀏覽器相容性

另見