关于Javascript 中 instanceof 与 typeof

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16566415/article/details/77743932

typeof

先看示例


    console.log(typeof '123');//string
    console.log(typeof 234);//number
    console.log(typeof false);//boolean
    console.log(typeof undefined);//undefined
    console.log(typeof null);//object
    console.log(typeof new String('123'));//object
    console.log(typeof function(){});//function
    console.log(typeof []);//array
    conosole.log(typeof new Number(12));//object

可以发现,基本类型(值类型)——number、string、boolean、undefined 可以使用typeof进行验证
而对于普通对象,函数,null这几中类型 typeof分别返回 object , function,object
这也说明null 是Object 类型

打开chrome,在控制台可以直接进行验证
typeof

instanceof

var arr = ['1','2','3'];
console.log(arr instanceof Array);//true;
var obj = new {};
console.log(obj instanceof Object);//true;
//... Number,String,Boolean 引用类型注意大写

还是使用chrome 的控制台验证
instanceof

与typeof 对比后小结:

typeof 用于检测基本类型,返回number、string、boolean、undefined,如果是object或者null 返回object,函数返回function

instanceof 用于判断某个引用变量(对象 )a 是否属于某个类型A,是返回true,不是就返回false;
这里的类型A 就是 js 自带的类型(Object、Function、Array、Number、String、Boolean…)以及自定义的类型(类)
如果使用 instanceof 操作符检测基本类型的值,则该操作符始终会返回 false,因为基本类型不是对象

猜你喜欢

转载自blog.csdn.net/qq_16566415/article/details/77743932