【一分钟JavaScript】判断数据类型typeof、instanceof、Object.prototype.toString()

208 阅读1分钟

JavaScript数据类型

基本数据类型(注意首字母都是大写)

  • Undefined
  • Null
  • Number
  • Boolean
  • String
  • Symbol

注意没有Function和Array类型!

复杂数据类型

  • Object

typeof

typeof用于判断数据类型,返回值为:

  • number
  • string
  • object
  • boolean
  • function
  • undefined
  • symbol

注意:

  • 注意首字母均是小写。
  • 没有null
  • 没有array
console.log(typeof undefined);//undefined
console.log(typeof null);//object
console.log(typeof 1);//number
console.log(typeof true);//boolean
console.log(typeof 'migao');//string
console.log(typeof [1,2,3]);//object
console.log(typeof function(){});//function
console.log(typeof Symbol());//symbol

null和undefined

  • null: 机器码均为0
  • undefined: 值为-2^30

instanceof

判断对象是否属于某种类型。注意是基本类型返回均为false,因为是值类型。

function A(){};
var a=new A();
a instanceof A  //返回true

instanceof的实现:

function instanceof(L, R) { //L是表达式左边,R是表达式右边
    var O = R.prototype;
    L = L.__proto__;
    while(true) {
        if (L === null)
            return false;
        if (L === O)
            return true;
        L = L.__proto__;
    }

判断数据类型

因为可以看到使用typeof判断基本类型,使用instanceof判断是否为实例; 而使用Object.prototype.toString().call()最为准确:

Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('hi') // "[object String]"
Object.prototype.toString.call({a:'hi'}) // "[object Object]"
Object.prototype.toString.call([1,'a']) // "[object Array]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(() => {}) // "[object Function]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"