首页 > Web开发 > 详细

JS isArray、typeof、instanceof

时间:2018-01-26 20:12:51      阅读:316      评论:0      收藏:0      [点我收藏+]

Array.isArray()

用来检验是不是数组

        var a = [1,2,3]
        console.log(typeof a);   // object
        console.log(Array.isArray(a));   // true

可以看出 typeof 并不能检验数组,虽然 Array.isArray() 可以检验数组,但是 IE8 都不兼容

        var a = [1,2,3]
        alert(Object.prototype.toString.call(a))  //  [object Array]

这个方法可以兼容IE8 以及以下的浏览器

 

typeof

        function foo(){}
        console.log(typeof foo);  // function
        console.log(typeof null); // object
        console.log(typeof undefined);  // undefined
        console.log(typeof ‘a‘);    //  string
        console.log(typeof 1);    // number

这里 null 是基本类型,不是一个对象,这个是 JS 的一个 bug。还有一个值得注意的地方:

console.log(undefined == null);  // true

因为在 JS 中 undefined 是派生自 null 的

 

instanceof

        function foo(){}
        var a = new foo()
        console.log(a instanceof foo);   // true

instanceof 是根绝原型链来查找的,如果函数 foo 的显示原型对象在 a 对象的隐式原型链上,则返回 true,否则返回 false

技术分享图片

 

 

 

 

绿色的就是对象 a 的原型链

JS isArray、typeof、instanceof

原文:https://www.cnblogs.com/lan1974/p/8360767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!