var arr = [1,2,3];
var obj = {name: "张三"};
typeof不能判断Array和Object
1.使用isArray()方法
if(Array.isArray){ //判断是否支持该方法
if(Array.isArray(arr)){
console.log("arryes");
}else{
console.log("arrno");
}
if(Array.isArray(obj)){
console.log("objyes");
}else{
console.log("objno");
}
}else{
console.log("不支持该方法")
}
2.instanceof 用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上
if (arr instanceof Array) {
console.log("arryes")
}
if (obj instanceof Array) {
console.log("objyes")
}
3.constructor 返回对象的构造函数
if(typeof arr == 'object' && arr.constructor == Array){
console.log("constructor yes");
}
4.prototype 原型对象
if(Object.prototype.toString.call(arr) == '[object Array]'){
console.log("prototype yes");
}
5.__proto__ 原型链
if(arr.__proto__ == Array.prototype){
console.log("__proto__ yes");
}
6.Object.getPrototypeOf()
if(Object.getPrototypeOf(arr) == Array.prototype){
console.log('Object.getPrototypeOf yes');
}
7. Array.prototype.isPrototypeOf
if (Array.prototype.isPrototypeOf(arr)) {
console.log("Array.prototype.isPrototypeOf yes")
}