前端知识采集JS相关Web前端之路

js检测数组的4种方法

2016-12-14  本文已影响59人  JokerPeng

定义一个数组:

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
上一篇 下一篇

猜你喜欢

热点阅读