aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/bigint/index.html
blob: 1ac067ad9837e5a77f7a3a5a302b615cc6456d0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
---
title: BigInt
slug: Web/JavaScript/Reference/Global_Objects/BigInt
translation_of: Web/JavaScript/Reference/Global_Objects/BigInt
---
<p>{{JSRef}}</p>

<p><strong><code>BigInt</code></strong> 是一种内置对象,它提供了一种方法来表示大于 <code>2^53 - 1</code> 的整数。这原本是 Javascript中可以用 {{JSxRef("Number")}} 表示的最大数字。<strong><code>BigInt</code></strong> 可以表示任意大的整数。</p>

<dl>
</dl>

<h2 id="描述">描述</h2>

<p>可以用在一个整数字面量后面加 <code>n</code> 的方式定义一个 <code>BigInt</code> ,如:<code>10n</code>,或者调用函数<code>BigInt()</code></p>

<pre class="brush: js"><code>const theBiggestInt = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// ↪ 9007199254740991n

const hugeString = BigInt("9007199254740991");
// ↪ 9007199254740991n

const hugeHex = BigInt("0x1fffffffffffff");
// ↪ 9007199254740991n

const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// ↪ 9007199254740991n</code></pre>

<p>它在某些方面类似于 {{jsxref("Global_Objects/Number", "Number")}} ,但是也有几个关键的不同点:不能用于 {{jsxref("Global_Objects/Math", "Math")}} 对象中的方法;不能和任何 {{jsxref("Global_Objects/Number", "Number")}} 实例混合运算,两者必须转换成同一种类型。在两种类型来回转换时要小心,因为 <code>BigInt</code> 变量在转换成 {{jsxref("Global_Objects/Number", "Number")}} 变量时可能会丢失精度。</p>

<h3 id="类型信息">类型信息</h3>

<p>使用 <code>typeof</code> 测试时, <code>BigInt</code> 对象返回 "bigint" :</p>

<pre class="brush: js"><code>typeof 1n === 'bigint'; // true
typeof BigInt('1') === 'bigint'; // true</code></pre>

<p>使用 <code>Object</code> 包装后, <code>BigInt</code> 被认为是一个普通 "object" :</p>

<pre class="brush: js"><code>typeof Object(1n) === 'object'; // true</code></pre>

<h3 id="运算">运算</h3>

<p>以下操作符可以和 <code>BigInt</code> 一起使用: <code>+</code>、`<code>*</code>`、`<code>-</code>`、`<code>**</code>`、`<code>%</code>` 。除 <code>&gt;&gt;&gt;</code> (无符号右移)之外的 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">位操作</a> 也可以支持。因为 <code>BigInt</code> 都是有符号的, <code>&gt;&gt;&gt;</code> (无符号右移)不能用于 <code>BigInt</code><a href="https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs">为了兼容 asm.js </a><code>BigInt</code> 不支持单目 (<code>+</code>) 运算符。</p>

<pre class="brush: js">const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
// ↪ 9007199254740991n

const maxPlusOne = previousMaxSafe + 1n;
// ↪ 9007199254740992n

const theFuture = previousMaxSafe + 2n;
// ↪ 9007199254740993n, this works now!

const multi = previousMaxSafe * 2n;
// ↪ 18014398509481982n

const subtr = multi – 10n;
// ↪ 18014398509481972n

const mod = multi % 10n;
// ↪ 2n

const bigN = 2n ** 54n;
// ↪ 18014398509481984n

bigN * -1n
// ↪ –18014398509481984n
</pre>

<p><code>/</code> 操作符对于整数的运算也没问题。可是因为这些变量是 <code>BigInt</code> 而不是 <code>BigDecimal</code> ,该操作符结果会向零取整,也就是说不会返回小数部分。</p>

<div class="warning">
<p><strong>警告:</strong>当使用 <code>BigInt</code> 时,带小数的运算会被取整。</p>
</div>

<pre class="brush: js">const expected = 4n / 2n;
// ↪ 2n

const rounded = 5n / 2n;
// ↪ 2n, not 2.5n

</pre>

<h3 id="比较">比较</h3>

<p><code>BigInt</code>{{jsxref("Global_Objects/Number", "Number")}} 不是严格相等的,但是宽松相等的。</p>

<pre class="brush: js">0n === 0
// ↪ false

0n == 0
// ↪ true</pre>

<p>{{jsxref("Global_Objects/Number", "Number")}}<code>BigInt</code> 可以进行比较。</p>

<pre class="brush: js">1n &lt; 2
// ↪ true

2n &gt; 1
// ↪ true

2 &gt; 2
// ↪ false

2n &gt; 2
// ↪ false

2n &gt;= 2
// ↪ true</pre>

<p>两者也可以混在一个数组内并排序。</p>

<pre class="brush: js">const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
// ↪  [4n, 6, -12n, 10, 4, 0, 0n]

mixed.sort();
// ↪ [-12n, 0, 0n, 10, 4n, 4, 6]</pre>

<p>注意被  <code>Object</code> 包装的 <code>BigInt</code>s 使用 object 的比较规则进行比较,只用同一个对象在比较时才会相等。</p>

<pre class="brush: js"><code>0n === Object(0n); // false
Object(0n) === Object(0n); // false

const o = Object(0n);
o === o // true</code></pre>

<h3 id="条件">条件</h3>

<p><code>BigInt</code> 在需要转换成 {{jsxref("Global_Objects/Boolean", "Boolean")}} 的时表现跟 {{jsxref("Global_Objects/Number", "Number")}} 类似:如通过 {{jsxref("Global_Objects/Boolean", "Boolean")}} 函数转换;用于 {{jsxref("Operators/Logical_Operators", "Logical Operators")}}  <code>||</code>, `<code>&amp;&amp;</code>`, 和 <code>!</code> 的操作数;或者用于在像 {{jsxref("Statements/if...else", "if statement")}} 这样的条件语句中。</p>

<pre class="brush: js">if (0n) {
  console.log('Hello from the if!');
} else {
  console.log('Hello from the else!');
}

// ↪ "Hello from the else!"

0n || 12n
// ↪ 12n

0n &amp;&amp; 12n
// ↪ 0n

Boolean(0n)
// ↪ false

Boolean(12n)
// ↪ true

!12n
// ↪ false

!0n
// ↪ true
</pre>

<h2 id="构造器">构造器</h2>

<dl>
 <dt><code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt">BigInt()</a></code></dt>
 <dd>创建{{jsxref("BigInt")}} 对象。</dd>
</dl>

<h2 id="静态方法">静态方法</h2>

<dl>
 <dt>{{JSxRef("BigInt.asIntN()")}}</dt>
 <dd>将 BigInt 值转换为一个 -2^(width-1) 与 2^(width-1) - 1 之间的有符号整数。</dd>
 <dt>{{JSxRef("BigInt.asUintN()")}}</dt>
 <dd>将一个 BigInt 值转换为 0 与 2^(width) - 1 之间的无符号整数。</dd>
</dl>

<h2 id="实例方法">实例方法</h2>

<dl>
 <dt>{{JSxRef("BigInt.prototype.toLocaleString()")}}</dt>
 <dd>返回此数字的 language-sensitive 形式的字符串。覆盖 {{JSxRef("Object.prototype.toLocaleString()")}}  方法。</dd>
 <dt>{{JSxRef("BigInt.prototype.toString()")}}</dt>
 <dd>返回以指定基数(base)表示指定数字的字符串。覆盖 {{JSxRef("Object.prototype.toString()")}} 方法。</dd>
 <dt>{{JSxRef("BigInt.prototype.valueOf()")}}</dt>
 <dd>返回指定对象的基元值。 覆盖 {{JSxRef("Object.prototype.valueOf()")}} 方法。</dd>
</dl>

<h2 id="使用建议">使用建议</h2>

<h3 id="转化">转化</h3>

<p>由于在 {{JSxRef("Number")}} 与 <code>BigInt</code> 之间进行转换会损失精度,因而建议仅在值可能大于2^53 时使用 <code>BigInt</code> 类型,并且不在两种类型之间进行相互转换。</p>

<h3 id="密码学">密码学</h3>

<p>由于对 <code>BigInt</code> 的操作不是常数时间的,因而 <code>BigInt</code> <a href="https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html">不适合用于密码学</a></p>

<h3 id="在_JSON_中使用">在 JSON 中使用</h3>

<p>对任何 <code>BigInt</code> 值使用 {{jsxref("JSON.stringify()")}} 都会引发 <code>TypeError</code>,因为默认情况下 <code>BigInt</code> 值不会在 <code>JSON</code> 中序列化。但是,如果需要,可以实现 <code>toJSON</code> 方法:</p>

<pre class="brush: js"><code>BigInt.prototype.toJSON = function() { return this.toString(); }</code></pre>

<p><code>JSON.stringify</code> 现在生成如下字符串,而不是抛出异常:</p>

<pre class="brush: js"><code>JSON.stringify(BigInt(1));
// '"1"'</code></pre>

<h2 id="例子">例子</h2>

<h3 id="Calculating_Primes">Calculating Primes</h3>

<pre class="brush: js">function isPrime(p) {
  for (let i = 2n; i * i &lt;= p; i++) {
    if (p % i === 0n) return false;
  }
  return true;
}

// Takes a BigInt as an argument and returns a BigInt
function nthPrime(nth) {
  let maybePrime = 2n;
  let prime = 0n;

  while (nth &gt;= 0n) {
    if (isPrime(maybePrime)) {
      nth -= 1n;
      prime = maybePrime;
    }
    maybePrime += 1n;
  }

  return prime;
}

nthPrime(20n)
// ↪ 73n</pre>

<h2 id="标准">标准</h2>

<table>
 <tbody>
  <tr>
   <th scope="col">标准</th>
   <th scope="col">状态</th>
  </tr>
  <tr>
   <td><a href="https://tc39.es/proposal-bigint/#sec-bigint-objects">BigInt</a></td>
   <td>第4阶段</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{Compat("javascript.builtins.BigInt")}}</p>

<h2 id="相关链接">相关链接</h2>

<ul>
 <li>{{JSxRef("Number")}}</li>
</ul>