js检测数组的4种方法

作者: JokerPeng | 来源:发表于2016-12-14 17:37 被阅读59次

定义一个数组:

var arr = [1,2,3];
typeof arr;   //object

可以发现用typeof只能测出arr是一个对象,因为类型操作符typeof返回值有6种:number,string,boolean,object,undefined和function。
我总结了4种方法检测数组:

1、instanceof
arr instanceof Array;    //true
2、isArray
Array.isArray(arr);      //true
3、constructor
arr.constructor === Array;    //true
4、由于在iframe中创建的Array并不共享prototype,此时可以:
function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]';
}

isArray(arr);            //true

相关文章

网友评论

    本文标题:js检测数组的4种方法

    本文链接:https://www.haomeiwen.com/subject/jaaimttx.html