js 数据类型与检测

在 ECMAScript 规范中,共定义了 7 种数据类型,分为基本类型和引用类型两大类:
1、基本类型(存于栈中):String、Number、Boolean、Symbol、undefined、null
2、引用类型(栈中存地址,指向堆中内容):Object

stack-heap.png

存储方式:
在JS中,基本数据类型直接存储在栈中,使用方便快捷,但内存小,不方便扩展。引用类型不是直接存储在栈中,而是在堆中开辟一块区域存储,在栈中的内容存放了指向堆中这块区域的地址。使用时,先是查到栈中的地址,再去堆中访问(这也是出现浅拷贝和深拷贝的原因)。

检测方法:
typeof、instanceof、constructor、Object.prototype.toString.call

1、typeof

typeof 是最简单的检测方法,但对引用类型检测不准确,还有typeof null === Object 为 true 这个问题,是一个存在已久的Bug。

返回值(字符串):
准确的:string、number、boolean、undefined、function
不准确的:object(检测array、object、null时返回)

2、instanceof

instanceof 检测引用数据类型,而不能检测基本数据类型

var arr = [], obj = {}, fn = () => {}, str = ‘aaa’

arr instanceof Array      // true
obj instanceof Object     // true
fn instanceof Function    // true
str instanceof String     // false

但是只要是在原型链上出现过构造函数都会返回true,所以这个检测结果不很准确

arr instanceof Object     // true,因为 Array.prototype.__proto__ === Object.prototype
3、constructor

constructor这个属性存在于构造函数的原型上,指向构造函数,对象可以通过proto在其所属类的原型上找到这个属性

var arr = []
arr.constructor === Array     // true

var obj = {}
obj.constructor   // Object

var str = 'aaa'
str.constructor   // String

var number = 12
number.constructor   // Number

var judge = true
judge.constructor    // Boolean

var _null = null;
_null.constructor    // 报错,Cannot read property 'constructor' of null

var _undefined = undefined;
_undefined.constructor  // 报错,Cannot read property 'constructor' of null

constructor是比较准确判断对象的所属类型的,但是如果有继承的话,就有问题了。

function Animal (species) {
  this.species = species
}
function Cat () {}
Cat.prototype = new Animal('cat')

var cat = new Cat()
cat.constructor    // Animal(function),而不是 Cat

Cat.prototype.constructor = Cat
cat.constructor    //  Cat
4、Object.prototype.toString.call()

应该是最准确的数据检测。(返回字符串)

Object.prototype.toString.call(1)        // [object Number]
Object.prototype.toString.call('a')      // [object String]
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 Array]
Object.prototype.toString.call({})      // [object Object]
Object.prototype.toString.call(() => {})  // [object Function]

可以用这个方法写一个检测类型函数:

function getType(value) {
  const str = Object.prototype.toString.call(value)
  return str.slice(8, -1)
}

getType(1)    // Number
getType({})   // Object
getType(() => {})    // Function
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容