数据类型

按照存储类型分类可分为基本类型和引用类型

  • 基本类型包含:string,number,boolean,null,undefined,symbol
  • 引用类型包含:Object

    • 对象类型还包含:Array,Function,Date,RegExp

如何判断数据类型

  • typeof
  • isArray
  • instanceof
  • Object.prototype.toString.call(xxx)

typeof

typeof返回一个标书数据类型的字符串.

var symbol = new Symbol()
typeof 'str';  // string
typeof 1;      // number
typeof false;  // boolean
typeof null;   // object
typeof undefined;  // undefined
typeof symbol; // symbol

typeof {};     // object
typeof [];     // object
typeof new Function();  // function
typeof new Date();  // object
typeof new RegExp();  // object

typeof的局限性在于对于引用类型的判断除了 function 之外返回的都是 object

isArray

用来判断是否是一个数组

Array.isArray([])  // true
Array.isArray({})  // false

实现一个 isArray

isArray = (data)=>{
  if(Object.prototype.toString.call(data) === '[object Array]'){
    retrun true
  }
  return false
}

instanceof

instanceof可以用来判断非基本类型的数据(也就只有对象一个啦)

原理:判断左边数据对象的原型链上是否有右边构造函数的 prototype 属性.也就是说,只要右边的 prototype 在左边的原型链上即可,因此instanceof在查找的过程中会遍历左边数据的原型链,直到找到右边数据的prototype

// 实现一个 instanceof
instanceof = (A,B) => {
    var L = A.__proto__
    var R = B.prototype
    while (true) {
        if(L === null) {
            return false
        }
        if(L === R) {
            return true
        }
        L = L.__proto__
    }
}

Object.prototype.toString.call(xxx)

原理:改变 this 的指向,指向变量的对象类型
Object.prototype.toString.call('str')  // [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(func)   // [object Function]
Object.prototype.toString.call(new Date())    // [object Date]
Object.prototype.toString.call(new Regexp())  // [object Regexp]
....

总结

关联知识点:

  • 原型链
  • this 指向
  • call/apply/bind

好好学习
7 声望2 粉丝

文章是自己在学习或踩到坑的过程中查找资料的总结,以便后期自己复习使用