JavaScript中的数据类型

263 阅读2分钟

在JavaScript中数据类型分为基本数据类型和引用数据类型。 基本数据类型可分为 Number、String、Boolean、Null、Undefined、Symbol(ES6新增数据类型)bigInt

  • 引用数据类型
    Object、Array、Date、Function、RegExp 其中基本数据类型的数据是直接存储在栈中;而引用数据类型的数据是存储在堆中,在栈中保存数据的引用地址,这个引用地址指向的是对应的数据,便于快速查找到堆内存中的对象。

栈内存是自动分配内存的,而堆内存是动态分配内存的,不会自动释放。因此每次使用完对象都要把它设置为null,从而减少无用内存的消耗,避免内存泄漏。

  • 判断数据类型的方式
    • typeof

但是typeof null的值为Object,无法区分是null还是Object,因为在JavaScript中,不同的对象都是使用二进制存储的,如果二进制前三位都是0的话,系统会判断为是Object类型,而null的二进制全是0,自然也就判断为Object。

扩展一下其他五种标识位:

000 对象
1 整型
010 双精度类型
100字符串
110布尔类型

  • instanceof 缺点:只能判断对象是否存在于目标对象的原型链上

constructor

Object.prototype.toString.call()

一种最好的基本类型检测方式

Object.prototype.toString.call() ;它可以区分 null 、 string 、boolean 、 number 、 undefined 、 array 、 function 、 object 、 date 、 math 数据类型。

缺点:不能细分为关系之间的实例

  // typeof
  typeof undefined // 'undefined' 
  typeof '11' // 'String' 
  typeof 11 // 'Number' 
  typeof false // 'Boolean' 
  typeof Symbol() // 'Symbol' 
  typeof Function // ‘function' 
  typeof null // ‘Object’ 
  typeof [] // 'Object' 
  typeof {} // 'Object'


  // instanceof
  function Zoo() { }
  var f1 = new Zoo();
  var d = new Number(1)


  console.log(f1 instanceof Zoo);// true
  console.log(d instanceof Number); //true
  console.log(123 instanceof Number);     
  //false   
  //不能判断字面量的基本数据类型


  // constructor
  var d = new Number(1)
  var e = 1
  function fn() {
    console.log("Zing");
  }
  var date = new Date();
  var arr = [1, 2, 3];
  var reg = /[hbc]at/gi;

  console.log(e.constructor);//ƒ Number() { [native code] }
  console.log(e.constructor.name);//Number
  console.log(fn.constructor.name) // Function 
  console.log(date.constructor.name)// Date 
  console.log(arr.constructor.name) // Array 
  console.log(reg.constructor.name) // RegExp




//Object.prototype.toString.call()
Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call({})  // 同上结果,加上call也ok
Object.prototype.toString.call(1)    // "[object Number]"
Object.prototype.toString.call('1')  // "[object String]"
Object.prototype.toString.call(true)  // "[object Boolean]"
Object.prototype.toString.call(function(){})  // "[object Function]"
Object.prototype.toString.call(null)   //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g)    //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([])       //"[object Array]"
Object.prototype.toString.call(document)  //"[object HTMLDocument]"
Object.prototype.toString.call(window)   //"[object Window]"