Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Extension of the ES6 value


May 08, 2021 ES6


Table of contents


1. Binary and octal notation

ES6 二进制 八进制 values, represented by the prefixes 0b (or 0B) and 0o (or 0O), respectively.

  1. 0b111110111 === 503 // true
  2. 0o767 === 503 // true

Starting with ES5, in strict mode, octals no longer allow the use of prefix 0, and ES6 is further clarified by using prefix 0o.

  1. // 非严格模式
  2. (function(){
  3. console.log(0o11 === 011);
  4. })() // true
  5. // 严格模式
  6. (function(){
  7. 'use strict';
  8. console.log(0o11 === 011);
  9. })() // Uncaught SyntaxError: Octal literals are not allowed in strict mode.

If you want to convert the string values of the 0b and 0o prefixes to ad- and ten-way, use Number method.

  1. Number('0b111') // 7
  2. Number('0o10') // 8

2. Number.isFinite(), Number.isNaN()

ES6 On the Number object, two new Number.isFinite() Number.isNaN() are available.

Number.isFinite() used to check whether a value is 有限的(finite) i.e. not Infinity.

  1. Number.isFinite(15); // true
  2. Number.isFinite(0.8); // true
  3. Number.isFinite(NaN); // false
  4. Number.isFinite(Infinity); // false
  5. Number.isFinite(-Infinity); // false
  6. Number.isFinite('foo'); // false
  7. Number.isFinite('15'); // false
  8. Number.isFinite(true); // false

Note that if the parameter type is not a numeric value, Number.isFinite returns false.

Number.isNaN() used to check whether a value is NaN

  1. Number.isNaN(NaN) // true
  2. Number.isNaN(15) // false
  3. Number.isNaN('15') // false
  4. Number.isNaN(true) // false
  5. Number.isNaN(9/NaN) // true
  6. Number.isNaN('true' / 0) // true
  7. Number.isNaN('true' / 'true') // true

If the parameter type is not NaN, Number.isNaN returns false.

The difference between them and the traditional global methods isFinite() and isNaN() is that the traditional method calls 数值 Number() to convert the value of a non-numeric value into a value and then determines that the two new methods are valid only for values, Number.isFinite() returns false for non-numeric values, And Number.isNaN() true only for NaN and non-NaN returns false only.

  1. isFinite(25) // true
  2. isFinite("25") // true
  3. Number.isFinite(25) // true
  4. Number.isFinite("25") // false
  5. isNaN(NaN) // true
  6. isNaN("NaN") // true
  7. Number.isNaN(NaN) // true
  8. Number.isNaN("NaN") // false
  9. Number.isNaN(1) // false

3. Number.parseInt(), Number.parseFloat()

ES6 ports the parseInt() and parseFloat() to the Number object, and the behavior remains completely the same.

  1. // ES5的写法
  2. parseInt('12.34') // 12
  3. parseFloat('123.45#') // 123.45
  4. // ES6的写法
  5. Number.parseInt('12.34') // 12
  6. Number.parseFloat('123.45#') // 123.45

The aim is to gradually reduce the global approach and make the language 模块化

  1. Number.parseInt === parseInt // true
  2. Number.parseFloat === parseFloat // true

4. Number.isInteger()

Number.isInteger() used to determine whether a value is an 整数

  1. Number.isInteger(25) // true
  2. Number.isInteger(25.1) // false

Inside JavaScript, integers and floats use the same storage method, so 25 and 25.0 are considered the same values.

  1. Number.isInteger(25) // true
  2. Number.isInteger(25.0) // true

If the argument is not a value, Number.isInteger returns false.

  1. Number.isInteger() // false
  2. Number.isInteger(null) // false
  3. Number.isInteger('15') // false
  4. Number.isInteger(true) // false

Note that because JavaScript is based on the IEEE 754 standard, values are stored in a 64-bit double format with numerical accuracy of up to 53 binary bits (1 hidden bit and 52 active bits). If the accuracy of the value exceeds this limit, the 54th and subsequent bits will be discarded, in which case Number.isInteger may misjudge.

  1. Number.isInteger(3.0000000000000002) // true

In the above code, the parameters of Number.isInteger clearly are not integers, but return true. The reason is that the precision of this scale reaches 16 binary bits after the scale point, and the binary bit exceeds 53 binary bits, resulting in the last 2 being discarded.

Similarly, if the absolute value of a value is less than Number.MIN_VALUE (5E-324), i.e. less than the minimum value that JavaScript can distinguish, it is automatically converted to 0. At this point, Number.isInteger also misjudges.

  1. Number.isInteger(5E-324) // false
  2. Number.isInteger(5E-325) // true

In the code above, 5E-325 returns true because the value is too small and is automatically converted to 0.

In summary, if the data accuracy requirements are high, it is not recommended to use Number.isInteger() to determine whether a value is an integer.

5. Number.EPSILON

ES6 On top of the Number object, a very small constant, Number.EPSILON Depending on the specification, it represents the difference between 1 and the 最小浮点数 1.

For 64-bit floats, the minimum floating point greater than 1 is equivalent to 1.00.001 in binary, with 51 consecutive zeros after the dot. This value minus 1 is equal to -52 squares of 2.

  1. Number.EPSILON === Math.pow(2, -52)
  2. // true
  3. Number.EPSILON
  4. // 2.220446049250313e-16
  5. Number.EPSILON.toFixed(20)
  6. // "0.00000000000000022204"

Number.EPSILON is actually the smallest accuracy 最小精度 If the error is less than this value, it can be considered meaningless, that is, there is no error.

The purpose of introducing such a small amount is to set 浮点数 floating-point calculations. We know that floating-point calculations are inaccurate.

  1. 0.1 + 0.2
  2. // 0.30000000000000004
  3. 0.1 + 0.2 - 0.3
  4. // 5.551115123125783e-17
  5. 5.551115123125783e-17.toFixed(20)
  6. // '0.00000000000000005551'

The above code explains why comparing 0.1 plus 0.2 with 0.3 results in false.

  1. 0.1 + 0.2 === 0.3 // false

Number.EPSILON can be used to “能够接受的误差范围” For example, the error range is set to -50 times (i.e., Number.EPSILON s Math.pow (2, 2), i.e. if the difference between the two floats is less than this value, we consider the two floats to be equal.

  1. 5.551115123125783e-17 < Number.EPSILON * Math.pow(2, 2)
  2. // true

Therefore, the essence of Number.EPSILON is an acceptable minimum margin of error.

  1. function withinErrorMargin (left, right) {
  2. return Math.abs(left - right) < Number.EPSILON * Math.pow(2, 2);
  3. }
  4. 0.1 + 0.2 === 0.3 // false
  5. withinErrorMargin(0.1 + 0.2, 0.3) // true
  6. 1.1 + 1.3 === 2.4 // false
  7. withinErrorMargin(1.1 + 1.3, 2.4) // true

The above code is a floating-point operation and an error check function is deployed.

6. Security integer and Number.isSafeInteger()

JavaScript can accurately represent integers ranging from -2^53 to 2^53 (without two endpoints), beyond which this value cannot be accurately represented.

  1. Math.pow(2, 53) // 9007199254740992
  2. 9007199254740992 // 9007199254740992
  3. 9007199254740993 // 9007199254740992
  4. Math.pow(2, 53) === Math.pow(2, 53) + 1
  5. // true

In the above code, after 53 times beyond 2, a number is not accurate.

ES6 Number.MAX_SAFE_INTEGER Number.MIN_SAFE_INTEGER two constants that represent the upper and lower limits of this range.

  1. Number.MAX_SAFE_INTEGER === Math.pow(2, 53) - 1
  2. // true
  3. Number.MAX_SAFE_INTEGER === 9007199254740991
  4. // true
  5. Number.MIN_SAFE_INTEGER === -Number.MAX_SAFE_INTEGER
  6. // true
  7. Number.MIN_SAFE_INTEGER === -9007199254740991
  8. // true

In the code above, you can see the limits that JavaScript can accurately represent.

Number.isSafeInteger() is used to determine whether an integer falls within this range.

  1. Number.isSafeInteger('a') // false
  2. Number.isSafeInteger(null) // false
  3. Number.isSafeInteger(NaN) // false
  4. Number.isSafeInteger(Infinity) // false
  5. Number.isSafeInteger(-Infinity) // false
  6. Number.isSafeInteger(3) // true
  7. Number.isSafeInteger(1.2) // false
  8. Number.isSafeInteger(9007199254740990) // true
  9. Number.isSafeInteger(9007199254740992) // false
  10. Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1) // false
  11. Number.isSafeInteger(Number.MIN_SAFE_INTEGER) // true
  12. Number.isSafeInteger(Number.MAX_SAFE_INTEGER) // true
  13. Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1) // false

The implementation of this function is simple, that is, compared with the two boundary values of the security integer.

  1. Number.isSafeInteger = function (n) {
  2. return (typeof n === 'number' &&
  3. Math.round(n) === n &&
  4. Number.MIN_SAFE_INTEGER <= n &&
  5. n <= Number.MAX_SAFE_INTEGER);
  6. }

When you actually use this function, you need to be careful. Verify that the results of the operation fall within the range of a safe integer, not just the results of the operation, but each value participating in the operation at the same time.

  1. Number.isSafeInteger(9007199254740993)
  2. // false
  3. Number.isSafeInteger(990)
  4. // true
  5. Number.isSafeInteger(9007199254740993 - 990)
  6. // true
  7. 9007199254740993 - 990
  8. // 返回结果 9007199254740002
  9. // 正确答案应该是 9007199254740003

In the code above, 90071999254740993 is not a secure integer, but Number.isSafeInteger returns the result, showing that the calculation is safe. This is because this number is outside the precision range, resulting in storage inside the computer in the form of 9007199254740992.

  1. 9007199254740993 === 9007199254740992
  2. // true

Therefore, if you only verify that the result of the operation is a safe integer, you are likely to get the wrong result. The following function validates both the number of operations and the result of the operation.

  1. function trusty (left, right, result) {
  2. if (
  3. Number.isSafeInteger(left) &&
  4. Number.isSafeInteger(right) &&
  5. Number.isSafeInteger(result)
  6. ) {
  7. return result;
  8. }
  9. throw new RangeError('Operation cannot be trusted!');
  10. }
  11. trusty(9007199254740993, 990, 9007199254740993 - 990)
  12. // RangeError: Operation cannot be trusted!
  13. trusty(1, 2, 3)
  14. // 3

7. Extension of the Math object

ES6 Math 17 to the Math object. All of these methods 静态方法 can only be called on math objects.

Math.trunc()

Math.trunc is used to remove a small part of a number and return an integer part.

  1. Math.trunc(4.1) // 4
  2. Math.trunc(4.9) // 4
  3. Math.trunc(-4.1) // -4
  4. Math.trunc(-4.9) // -4
  5. Math.trunc(-0.1234) // -0

For non-values, Math.trunc uses the Number to convert it first to a value.

  1. Math.trunc('123.456') // 123
  2. Math.trunc(true) //1
  3. Math.trunc(false) // 0
  4. Math.trunc(null) // 0

For empty values and values that cannot be intercepted, return NaN.

  1. Math.trunc(NaN); // NaN
  2. Math.trunc('foo'); // NaN
  3. Math.trunc(); // NaN
  4. Math.trunc(undefined) // NaN

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.trunc = Math.trunc || function(x) {
  2. return x < 0 ? Math.ceil(x) : Math.floor(x);
  3. };

Math.sign()

Math.sign method is used to determine whether a number is positive, negative, or zero. For non-values, they are converted to values first.

It 五种

  • The argument is positive and returns a value of 1;
  • The argument is negative and returns -1;
  • The argument is 0 and returns 0;
  • The parameter is -0 and returns -0;
  • Other values, return NaN.

  1. Math.sign(-5) // -1
  2. Math.sign(5) // +1
  3. Math.sign(0) // +0
  4. Math.sign(-0) // -0
  5. Math.sign(NaN) // NaN

If the argument is non-numeric, it is automatically converted to a value. For values that cannot be converted to values, a NaN is returned.

  1. Math.sign('') // 0
  2. Math.sign(true) // +1
  3. Math.sign(false) // 0
  4. Math.sign(null) // 0
  5. Math.sign('9') // +1
  6. Math.sign('foo') // NaN
  7. Math.sign() // NaN
  8. Math.sign(undefined) // NaN

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.sign = Math.sign || function(x) {
  2. x = +x; // convert to a number
  3. if (x === 0 || isNaN(x)) {
  4. return x;
  5. }
  6. return x > 0 ? 1 : -1;
  7. };

Math.cbrt()

Math.cbrt() method is used to calculate the cubic root of 立方根

  1. Math.cbrt(-1) // -1
  2. Math.cbrt(0) // 0
  3. Math.cbrt(1) // 1
  4. Math.cbrt(2) // 1.2599210498948732

For non-numeric values, the Math.cbrt() method also uses the Number() method to convert it to a numeric method.

  1. Math.cbrt('8') // 2
  2. Math.cbrt('hello') // NaN

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.cbrt = Math.cbrt || function(x) {
  2. var y = Math.pow(Math.abs(x), 1/3);
  3. return x < 0 ? -y : y;
  4. };

Math.clz32()

Math.clz32() the argument into a 32-bit unsigned integer and returns how many leading 0s are in this 32-bit value.

  1. Math.clz32(0) // 32
  2. Math.clz32(1) // 31
  3. Math.clz32(1000) // 22
  4. Math.clz32(0b01000000000000000000000000000000) // 1
  5. Math.clz32(0b00100000000000000000000000000000) // 2

In the above code, 0 is all binary, so there are 32 leading 0s; the binary form of 0b1111101000, which has a total of 10 bits, so there are 22 leading 0s out of 32 bits.

The function name clz32 comes from the abbreviation "count zero bits in 32-bit binary representation of a number" (the number of leading 0s in the 32-bit binary form of a number is calculated).

The left-shift operator is directly related to the Math.clz32 method.

  1. Math.clz32(0) // 32
  2. Math.clz32(1) // 31
  3. Math.clz32(1 << 1) // 30
  4. Math.clz32(1 << 2) // 29
  5. Math.clz32(1 << 29) // 2

For numbers, the Math.clz32 method considers only the integer part.

  1. Math.clz32(3.2) // 30
  2. Math.clz32(3.9) // 30

For empty values or other types of values, the Math.clz32 method converts them to values before they are calculated.

  1. Math.clz32() // 32
  2. Math.clz32(NaN) // 32
  3. Math.clz32(Infinity) // 32
  4. Math.clz32(null) // 32
  5. Math.clz32('foo') // 32
  6. Math.clz32([]) // 32
  7. Math.clz32({}) // 32
  8. Math.clz32(true) // 31

Math.imul()

Math.imul returns the result of multiplying two numbers by 32-bit signed integers, and returns a 32-bit signed integer.

  1. Math.imul(2, 4) // 8
  2. Math.imul(-1, 8) // -8
  3. Math.imul(-2, -2) // 4

If only the last 32 bits are considered, in most cases Math.imul(a, b) has the same result as a b, i.e. the method is equivalent to the effect of (a b)|0 (partial overflow of more than 32 bits). T his method needs to be deployed because JavaScript has precision limitations, and values above 53 times of 2 cannot be accurately represented. This means that for the multiplication of large numbers, low-bit values are often inaccurate, and the Math.imul method returns the correct low-bit values.

  1. (0x7fffffff * 0x7fffffff)|0 // 0

This multiplication calculation above returns a result of 0. H owever, since the lowest bits of both binary numbers are 1, this result is certainly incorrect, because according to binary multiplication, the binary lowest bit of the calculated result should also be 1. T his error is because their product exceeds 53 times of 2, and JavaScript can't save the extra precision, turning the low value into 0. The Math.imul method returns the correct value of 1.

  1. Math.imul(0x7fffffff, 0x7fffffff) // 1

Math.fround()

Math.fround method returns a number of 32-bit single-precision floating-point forms.

For a 32-bit single-precision format, numerical precision is 24 binary bits (1-bit hidden bit and 23-bit valid bit), so for integers between -224 and 224 (excluding two endpoints), the return result is consistent with the parameter itself.

  1. Math.fround(0) // 0
  2. Math.fround(1) // 1
  3. Math.fround(2 ** 24 - 1) // 16777215

If the absolute value of the argument is greater than 224, the returned result begins to lose precision.

  1. Math.fround(2 ** 24) // 16777216
  2. Math.fround(2 ** 24 + 1) // 16777216

The main function of math.fround method is to convert 64-bit double-precision floating point to 32-bit single-precision floating point. If the scale is more than 24 binary bits, the return value will be different from the original value, otherwise the return value will remain the same (i.e. consistent with the 64-bit double).

  1. // 未丢失有效精度
  2. Math.fround(1.125) // 1.125
  3. Math.fround(7.25) // 7.25
  4. // 丢失精度
  5. Math.fround(0.3) // 0.30000001192092896
  6. Math.fround(0.7) // 0.699999988079071
  7. Math.fround(1.0000000123) // 1

For NaN and Infinity, this method returns the original value. For other types of non-values, the Math.fround method converts them to values and returns single-precision floats.

  1. Math.fround(NaN) // NaN
  2. Math.fround(Infinity) // Infinity
  3. Math.fround('5') // 5
  4. Math.fround(true) // 1
  5. Math.fround(null) // 0
  6. Math.fround([]) // 0
  7. Math.fround({}) // NaN

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.fround = Math.fround || function (x) {
  2. return new Float32Array([x])[0];
  3. };

Math.hypot()

Math.hypot returns the square root of the sum of the squares of all parameters.

  1. Math.hypot(3, 4); // 5
  2. Math.hypot(3, 4, 5); // 7.0710678118654755
  3. Math.hypot(); // 0
  4. Math.hypot(NaN); // NaN
  5. Math.hypot(3, 4, 'foo'); // NaN
  6. Math.hypot(3, 4, '5'); // 7.0710678118654755
  7. Math.hypot(-3); // 3

In the above code, the square of 3 plus the square of 4 equals the square of 5.

If the argument is not a value, the Math.hypot method turns it into a value. NaN is returned as long as there is a parameter that cannot be converted to a value.

The number-to-right method

ES6 added four new 对数 methods.

(1) Math.expm1()

Math.expm1 (x) returns ex - 1, i.e. Math.exp(x) - 1.

  1. Math.expm1(-1) // -0.6321205588285577
  2. Math.expm1(0) // 0
  3. Math.expm1(1) // 1.718281828459045

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.expm1 = Math.expm1 || function(x) {
  2. return Math.exp(x) - 1;
  3. };

(2)Math.log1p()

The Math.log1p(x) method returns a natural log of 1 x, i.e. .log (1 x). If x is less than -1, return NaN.

  1. Math.log1p(1) // 0.6931471805599453
  2. Math.log1p(0) // 0
  3. Math.log1p(-1) // -Infinity
  4. Math.log1p(-2) // NaN

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.log1p = Math.log1p || function(x) {
  2. return Math.log(1 + x);
  3. };

(3)Math.log10()

Math.log10(x) returns a log of x with a base of 10. If x is less than 0, NaN is returned.

  1. Math.log10(2) // 0.3010299956639812
  2. Math.log10(1) // 0
  3. Math.log10(0) // -Infinity
  4. Math.log10(-2) // NaN
  5. Math.log10(100000) // 5

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.log10 = Math.log10 || function(x) {
  2. return Math.log(x) / Math.LN10;
  3. };

(4)Math.log2()

Math.log2(x) returns a log of x with a base of 2. If x is less than 0, NaN is returned.

  1. Math.log2(3) // 1.584962500721156
  2. Math.log2(2) // 1
  3. Math.log2(1) // 0
  4. Math.log2(0) // -Infinity
  5. Math.log2(-2) // NaN
  6. Math.log2(1024) // 10
  7. Math.log2(1 << 29) // 29

For environments that do not have this method deployed, you can simulate it with the following code.

  1. Math.log2 = Math.log2 || function(x) {
  2. return Math.log(x) / Math.LN2;
  3. };

The two-curve function method

ES6 added six new 双曲函数方法

  • Math.sinh(x) returns x's hyperbolic sine
  • Math.cosh(x) returns x's hyperbolic cosine
  • Math.tanh(x) returns x's hyperbolic tangent
  • Math.asinh(x) returns x's inverse hyperbolic sine
  • Math.acosh(x) returns x's anti-hyperbolic cosine (inverse hyperbolic cosine)
  • Math.atanh(x) returns x's inverse hyperbolic tangent

8. Exponential operator

ES2016 has added a 指数运算符 operator.

  1. 2 ** 2 // 4
  2. 2 ** 3 // 8

One feature of this operator is the right binding, not the common left binding. When multiple exponential operators are connected, they are calculated from the far right.

  1. // 相当于 2 ** (3 ** 2)
  2. 2 ** 3 ** 2
  3. // 512

In the above code, the second exponential operator is calculated first, not the first.

The exponential operator can be combined with an equal sign to form a new assignment operator.

  1. let a = 1.5;
  2. a **= 2;
  3. // 等同于 a = a * a;
  4. let b = 4;
  5. b **= 3;
  6. // 等同于 b = b * b * b;

9. BigInt data type

Brief introduction

All JavaScript numbers are saved as 64-bit floating-point numbers, which places two major limitations on the display of values. O ne is that the accuracy of the values can only be up to 53 binary bits (equivalent to 16 heliod bits), which is larger than the integers in this range, which JavaScript cannot accurately represent, making JavaScript unsuitable for scientific and financial calculations. The second is the value of 1024 times greater than or equal to 2, which JavaScript cannot represent and returns to Infinity.

  1. // 超过 53 个二进制位的数值,无法保持精度
  2. Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
  3. // 超过 2 的 1024 次方的数值,无法表示
  4. Math.pow(2, 1024) // Infinity

ES2020 introduces a new data BigInt(大整数) solve this problem. BigInt is used only to represent integers, and there is no limit to the number of digits, and integers of any number of digits can be accurately represented.

  1. const a = 2172141653n;
  2. const b = 15346349309n;
  3. // BigInt 可以保持精度
  4. a * b // 33334444555566667777n
  5. // 普通整数无法保持精度
  6. Number(a) * Number(b) // 33334444555566670000

To distinguish it from the Number type, data of the BigInt type must be suffixed n.

  1. 1234 // 普通整数
  2. 1234n // BigInt
  3. // BigInt 的运算
  4. 1n + 2n // 3n

BigInt can also use a variety of pre-orders, with the suffix n.

  1. 0b1101n // 二进制
  2. 0o777n // 八进制
  3. 0xFFn // 十六进制

BigInt and normal integers are two values that are not equal.

  1. 42n === 42 // false

The typeof operator returns a bigint for data of the BigInt type.

  1. typeof 123n // 'bigint'

BigInt can use a negative sign (- ), but not a positive sign ( , ) because it conflicts with the asm .js system.

  1. -42n // 正确
  2. +42n // 报错

JavaScript could not have calculated the order of 70 (i.e. 70!) before. ), because the accuracy that can be represented is exceeded.

  1. let p = 1;
  2. for (let i = 1; i <= 70; i++) {
  3. p *= i;
  4. }
  5. console.log(p); // 1.197857166996989e+100

Now that you support large integers, you can count, the browser's developer tools run the following code, OK.

  1. let p = 1n;
  2. for (let i = 1n; i <= 70n; i++) {
  3. p *= i;
  4. }
  5. console.log(p); // 11978571...00000000n

BigInt object

JavaScript natively provides a BigInt 对象 used as a 构造函数 values of the BigInt type. The conversion rule is basically the same as Number(), converting other types of values to BigInt.

  1. BigInt(123) // 123n
  2. BigInt('123') // 123n
  3. BigInt(false) // 0n
  4. BigInt(true) // 1n

The BigInt() constructor must have parameters, and the parameters must be converted to values normally, and the following usages will be misalmeanor.

  1. new BigInt() // TypeError
  2. BigInt(undefined) //TypeError
  3. BigInt(null) // TypeError
  4. BigInt('123n') // SyntaxError
  5. BigInt('abc') // SyntaxError

In the above code, it is particularly noteworthy that the string 123n cannot be resolved to the Number type, so an error is reported.

If the argument is a small number, an error is also reported.

  1. BigInt(1.5) // RangeError
  2. BigInt('1.5') // SyntaxError

The BigInt object inherits two instance methods of the Object object.

  • BigInt.prototype.toString()
  • BigInt.prototype.valueOf()

It also inherits an instance method of the Number object.

  • BigInt.prototype.toLocaleString()

In addition, three static methods are provided.

  • BigInt.asUintN (width, BigInt): Given the BigInt changes to a value between 0 and 2width - 1.
  • BigInt.asIntN (width, BigInt): Given the BigInt turns to the corresponding value between -2width - 1 to 2width - 1 - 1.
  • BigInt.parseInt (string, radix)): Approximate to Number.parseInt(), convert a string into a specified-made BigInt.

  1. const max = 2n ** (64n - 1n) - 1n;
  2. BigInt.asIntN(64, max)
  3. // 9223372036854775807n
  4. BigInt.asIntN(64, max + 1n)
  5. // -9223372036854775808n
  6. BigInt.asUintN(64, max + 1n)
  7. // 9223372036854775808n

In the code above, max is the maximum value that a 64-bit signed BigInt can represent. I f you add 1n to this value, BigInt.asIntN() will return a negative value because the new bit will be interpreted as a sign bit. The BigInt.asUintN() method returns the result correctly because there are no sign bits.

If the number of digits specified by BigInt.asIntN() and BigInt.asUintN() is less than the number of digits of the value itself, the bit of the head will be discarded.

  1. const max = 2n ** (64n - 1n) - 1n;
  2. BigInt.asIntN(32, max) // -1n
  3. BigInt.asUintN(32, max) // 4294967295n

In the code above, max is a 64-bit BigInt, and if you switch to 32 bits, the first 32 bits are discarded.

The following is an example of BigInt.parseInt().

  1. // Number.parseInt() 与 BigInt.parseInt() 的对比
  2. Number.parseInt('9007199254740993', 10)
  3. // 9007199254740992
  4. BigInt.parseInt('9007199254740993', 10)
  5. // 9007199254740993n

In the above code, the Number.parseInt method returns inaccurate results because the valid number exceeds the maximum, and the BigInt.parseInt method correctly returns the corresponding BigInt.

For binary arrays, BigInt adds two new types, BigUint64Array and BigInt64Array, both of which return 64-bit BigInt. The instance methods of the DataView object DataView.prototype.getBigInt64() and DataView.prototype.getBigUint64() also return BigInt.

Conversion rules

You can convert BigInt to Number() String() by using the three methods: Boolean() Numeric, and String().

  1. Boolean(0n) // false
  2. Boolean(1n) // true
  3. Number(1n) // 1
  4. String(1n) // "1"

In the code above, note the last example, and the suffix n disappears when it turns into a string.

Also, take the anti-operator (! You can also convert BigInt to Boolean.

  1. !0n // true
  2. !1n // false

Mathematical operations

In terms of mathematical operations, the BigInt types of the four binary operators, , - , , and , are consistent with the behavior of the Number type. Division / will give up the small part and return an integer.

  1. 9n / 5n
  2. // 1n

Almost all numeric operators can be used in BigInt, with two exceptions.

  • Unsigned right shift operator
  • The one-dollar positive operator

The above two operators are used in BigInt to report errors. T he former is because the operator is unsigned, but BigInt is always signed, which makes the operation meaningless and exactly the same as the right-shift operator. The latter is because the 100 operator s always returns the Number type .js in the asm .js, which is specified as an error in order not to break the asm.js

BigInt cannot be mixed with normal values.

  1. 1n + 1.3 // 报错

The above code is wrong because whether it is returned bigInt or Number, it can result in the loss of precision information. For example, if you return the BigInt type, the small part of 0.5 is lost, and if you return the Number type, the effective accuracy can only be maintained at 53 bits, resulting in a decrease in accuracy.

For the same reason, if the parameters of a standard library function are expected to be number type, but you get a BigInt, you will report an error.

  1. // 错误的写法
  2. Math.sqrt(4n) // 报错
  3. // 正确的写法
  4. Math.sqrt(Number(4n)) // 2

In the above code, Math.sqrt's parameters are expected to be Number type, and if it is BigInt, it will be reported as an error, and the type must be turned around using the Number method before it can be calculated.

Inside .js, | 0 follows a value and returns a 32-bit integer. Depending on the rules that cannot be mixed with the Number type, BigInt will report an error if | 0 is performed with the number type.

  1. 1n | 0 // 报错

Other operations

The Boolean value for BigInt is consistent with the Number type, i.e. 0n turns false and the other values turn true.

  1. if (0n) {
  2. console.log('if');
  3. } else {
  4. console.log('else');
  5. }
  6. // else

In the code above, 0n corresponds to false, so the else clause is entered.

Comparison operators, such as the equivalent operator, allow BigInt to mix calculations with other types of values because doing so does not lose precision.

  1. 0n < 1 // true
  2. 0n < true // true
  3. 0n == 0 // true
  4. 0n == false // true
  5. 0n === 0 // false

When BigInt is mixed with strings, it is converted to a string before it is performed.

  1. '' + 123n // "123"