JavaScript数据类型和检测

JavaScript的数据类型分为值类型(基本数据类型)和引用类型(对象类型)。

值类型

值类型有 Null、Undefined、Boolean、String、Number、BigInt、Symbol类型。
值类型的数据是确定的,内存空间可分配,按值存放在栈中。

值不可变:原始值是不可更改的(str[1]='q'不生效),但是可以重新赋值,相当于返回了一个新的值。

Number:JavaScript 中只有一种数字类型:基于 IEEE 754 标准的双精度 64 位二进制格式的值(-(253 -1) 到 253 -1)。包括NaN,-Infinity/+Infinity,-0/+0 。

引用类型

引用类型主要就是Object([],{},function(){})内置对象有Function,Array,Math,Date,RegExp
引用类型存放在堆中,值是可变的(arr[0]=1),内存要根据情况分配,所以变量其实是一个存放在栈中的指针。

let str = 'string';
let number = 10;
let value = null;
let obj = {value:1};
let arr = [1,2]

在这里插入图片描述

数据检测的四种方式

1.typeof

typeof操作符,返回操作数的类型

typeof '';  //string
typeof 10;  //number
typeof false;  //boolean
typeof Symbol();  //symbol
typeof undefined;  //undefined
typeof null;  //object
typeof {};  //object
typeof [];  //object
typeof function(){};  //function
typeof new String();  //object
typeof new Number();  //object
typeof new Boolean();  //object

typeof只能用来判断是哪种基本数据类型,不能判断是哪种对象类型。
其中对null的判断是 typeof null; //object,这是js中的一个历史遗留bug,null是基本数据类型也就是值类型,这里他“期望”null是一个空指针。
typeof 对于new的数据类型都会判断为object。

2. instanceOf

instanceOf用来检测对象的原型链上是否存在某构造函数的prototype属性,返回Boolean值。

function Person(params) {
  this.name = params
}
let wang = new Person("w")

wang instanceof Person;  //true
Person instanceof Function;  //true
wang instanceof Object;  //true

可以检测A是否是B的实例,不能检测 null 和 undefined。

[] instanceof Array;  //true
new Object() instanceof Object;  //true
new Function() instanceof Function;  //true
new Date() instanceof Date;  //true
new RegExp() instanceof RegExp;  //true

在这里插入图片描述

3.constrcutor

构造函数,类的原型上都会有一个constructor属性,存储的是当前类本身。

let [n,arr] = [10,[]];
n.constructor ===  Number  // true
arr.constructor === Array  // true
arr.constructor = 'Person'
arr.constructor === Array  //false

缺点:容易被修改

4.Object.prototype.toString.call()

toString()未被覆盖时,返回"[object type]",其中type是对象的类型。

Object.prototype.toString.call('')  //[object String]
Object.prototype.toString.call(1)   //[object Number]
Object.prototype.toString.call(true)  //[object Boolean]
Object.prototype.toString.call(null)  //[object Null]
Object.prototype.toString.call(undefined)  //[object Undefined]
Object.prototype.toString.call({})  //[object Object]
Object.prototype.toString.call([])  //[object Array]
Object.prototype.toString.call(function () {  })  //[object Function]
Object.prototype.toString.call(/a/g)  //[object RegExp]
Object.prototype.toString.call(new Date())  //[object Date]

检测类型最准确的就是Object.prototype.toString
可以抽离出来一个类型检测的方法

function getType(val){
  return Object.prototype.toString.call(val).slice(8,-1)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值