typeof 和 instanceof

1、typeof 用来用来判断一个变量的类型

(1)number  数字类型

typeof(123);     // number
typeof(NaN);    // number

(2)string  字符串类型

typeof('123');  // string

(3)boolean 布尔类型

typeof(true);  // boolean

(4)object        对象类型->对象、数组、null、JSON、Math 返回都是object

typeof({});         // object
typeof([]);         // object
typeof(null);       // object
typeof(Math);       // object
typeof(JSON);       // object

(5)function      函数类型 -> eval、自定义函数、构造函数(可以用new执行的)返回都是function

typeof(eval);        // function
typeof(()=>{});      // function
typeof(Object);      // function
typeof(Date);        // function

(6)undefined     不存在的变量、函数或者undefined

typeof(undefined);     // undefined
typeof(abc);           // undefined

注意:typeof 在判断 null 的时候出现问题,因为 null 的所有机器码均为0,直接被当做了对象看待。

null instanceof null  // TypeError: Right-hand side of 'instanceof' is not an object

null 直接被判断为不是 object ,这是一个 JavaScript 的历史遗留问题。

判断类型更好的方法: Object.prototype.toString.call(variate)

可以识别出 Number String Object Math JSON Array Function Null Boolean Undefined Symbol 类型

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(JSON)     //  "[object JSON]"            单独识别出 JSON 对象

Object.prototype.toString.call(Math)     //  "[object Math]"            单独识别出 Math 对象

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]"           这里的 null 就能被识别出来了

Object.prototype.toString.call(undefined)    // "[object Undefined]"

Object.prototype.toString.call(Symbol(1))    // "[object Symbol]"

2、instanceof 用来判断某个对象是否属于另一个函数构造

使用 typeof 运算符时判断引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回”object”。

因此ECMAScript引入了另一个Java运算符->Instanceof,用于识别正在处理的对象的类型。

缺点:instanceof 方法要求开发者明确地确认对象为某特定类型;只能判断引用类型。

//可以应用在对象类型深拷贝环节
let obj = [1,2,3,{a:1,b:[11,22]}];       // 需要深拷贝的引用类型变量

function deepCopy(obj){
    let temp = obj instanceof Array ? [] : {};  //不是数组就是对象
    
    for(let i in obj){          //数组、对象都能 for in 遍历  
          if(typeof(obj[i])==='object'){
                 temp[i] = deepCopy(obj[i])
           }else{
                 temp[i] = obj[i];
           }  
    }   
    return temp;      
}    

一些使用 instanceof 的判断案例

Object instanceof Function;        // true   所有构造函数都是Function的实例
Function instanceof Object;         // true
Object instanceof Object;          // true

 

posted @ 2019-09-27 11:27  牛龙飞  阅读(185)  评论(0编辑  收藏  举报