1.使用ES5中的Array.isArray()方法
function isArray(obj){
return Array.isArray(obj);
}
2.使用Object原生的toString()方法
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]';
}
對(duì)象原型方法toString會(huì)返回一個(gè)[object NativeConstructorName]格式字符串,指定了對(duì)象的原生構(gòu)造函數(shù)名,一個(gè)普通對(duì)象則會(huì)返回[object Object]
同理号涯,可以用這個(gè)方法判斷是否為原生函數(shù):
function isFunction(obj){
return Object.prototype.toString.call(obj) === '[object Function]';
}
3.對(duì)象__proto__屬性指向其原型對(duì)象(取決于瀏覽器實(shí)現(xiàn),不支持IE)
function isArray(obj){
return obj.__proto__ === Array.prototype;
}
實(shí)例如果是某個(gè)構(gòu)造函數(shù)構(gòu)造出來(lái)的那么 它的__proto__是指向構(gòu)造函數(shù)的 prototype屬性