JavaScript:BigInt

If it can be achieved, remember to like and share, thank you~

Insert image description here

The latest ES2020 defines nine data types. The six data types are primitives, checked by the typeof operator, null, Object and Function. The primitives are undefined, boolean, number, string, symbol, and the new primitive is BigInt. For the first time in JavaScript, we can store numbers greater than Number, in other words, integers greater than 2 53 - 1.

We can create a BigInt by appending **n to the end of the integer or using the constructor ****BigInt()**

const big = 12345n;
typeof big; // "bigint"
const sameBig = BigInt("12345"); //12345n
const oneMoreSame = BigInt(12345); //12345n

Operating with BigInt

Operations like +, *, -, **, % can be used like numbers.

const huge = 20n + 4n; //24n
const oneMore = 20n - 4n; //16n
const oneBig = 20n ** 4n; //160000n

Bitwise operators can also be used, except >>> (zero-padded right shift), since all BigInts are signed.

const big = 20n & 4n; //4n

We need to remember that the result of the / operation will be rounded towards 0 like any other number.

const big = 20n / 4n; //5n
const huge = 20n / 3n; //6n

One Yuan+ is not supported.

const big = +3n; //Error: Cannot convert a BigInt value to a number

Comparisons and operations with other types

You cannot mix BigInt with other types, not even Number. Something like this will give you an error.

const big = 20n + 4; //Error: Cannot mix BigInt and other types

But we can convert them.

const big = 20n + BigInt(4); //24n
const huge = Number(20n) + 4; //24

Using strings, you can concatenate BigInt.

const big = 20n + "4"; //"204"

BigInt is loosely equal to Number, but not strictly equal.

20n == 20; //true
20n === 20; //false

Number and BigInt data types can be compared naturally.

20 > 10n; //true
20n >= 20; // true

We can see the similarities between Number and BigInt, but the important point is that it cannot be used with the methods in the built-in Math object. On the other hand, BigInt behaves like Number when used with logical operators (||, &&, !), converted to Boolean, and used in conditional tests.

const big = Boolean(20n); //true
!big; //false

Guess you like

Origin blog.csdn.net/Gas_station/article/details/131829494