bigInt; instanceof和typeof

一、bigInt:

 BigInt是一种新的数据类型,用于当整数值大于Number数据类型所支持的 范围时。这种数据类型允许我们安全地对 大整数 执行算数操作,表示高分辨率的时间戳、

使用大整数id等等,而不需要使用库去处理大整数。

Js中的Number类型只能安全地表示(-(2^53 - 1)) 到((2^53-1)),任何超出此范围的整数值都可能失去精度。因此会出现一些安全性的问题。

如何创建并使用BigInt:

创建:只需要在数值末尾追加n即可。

console.log(9999999999999999999999999999n);

console.log(9999999999999999999999999999);

另一种创建:BigInt('99999999999999999999999');

简单使用:

10n+20n  // ->  30n

10n-20n // -> -10n

+10n //  ->typeError

-10n //  -> -10n

10n * 20n  // -> 200n

20n / 10n // -> 2n

23n % 10n  // -> 3n

10n ** 3n // -> 1000n

const a = 10n;

++x; // ->  11n;

--x; //  9n

console.log(typeof a);  // ->  "bigint"

由以上示例可以知道+10n会报错,这是因为 + 符号的特殊性,对于所有类型的参数与 +号一起使用时,其实相当于是在与number值做加法;

如  + new Date() 可以获取当前的时间戳: new Date()会转换为Number;

因此+ 10n 要把10n转换为number,但是由于这个隐式类型转换可能丢失信息,所以不允许在bigInt和number之间进行转换。所以会报typeerror。

如下:10 + 10n 也会报typeerror,math.max(2n, 4n)也会报typeerror(max函数要求传入的参数是number)。

当boolean和bigInt类型相遇时,bigInt的处理方式与number一样,即除了0n,其他bigInt都是ture。

if(3n) {}  // -> true

if(0n) {}  // -> false

二、使用typeof和instanceof来判断数据类型

1.typeof:

首先使用typeof判断基础数据类型:

typeof 1  // 'number'

typeof '1'  // 'string'

typeof undefined  // 'undefined'

typeof true  // 'boolean'

typeof Symbol() // 'symbol'

typeof 10n // 'bigInt'

typeof null // 'object'  

结论——> 基础数据类型中除了null,其他基础数据类型都可以调用typeof显示正确的类型。

但对于引用数据类型,除了函数之外,都会显示'object',

typeof []  // -> 'object'

typeof {} // -> 'object'

typeof console.log // 'function'

因此采用typeof判断对象数据类型是不合适的,采用instanceof会更好,instanceof的原理是基于原型链的查询,只要

处于原型链中,判断永远为true。

对于所有基础数据类型,使用instanceof返回的值为false。因此使用instanceof可以很好的去判断基础数据类型。

猜你喜欢

转载自www.cnblogs.com/kkkwoniu/p/12057316.html
今日推荐