第一种:
var arr = [1,2];
var obj = {};
var str1 = "str1";
var str2 = new String("str2");
console.log(arr instanceof Array);//返回 true
console.log(obj instanceof Object);//返回 true
//=====================================================
//另外 判断一个对象是不是另一个对象的实例;
//A instanceof B 要判断A对象的原型链上有没有B; 前提是 A是引用类型;
console.log(arr instanceof Object);//返回true
console.log(str2 instanceof Object)//返回true
console.log(str1 instanceof Object)//返回false
第二种:
var obj = {};
var arr = [];
arr.constructor==Array;//返回true
obj.constructor==Object;//返回true
arr.constructor==Object;//返回false
obj.constructor==Array;//返回false
第三种:
console.log(Object.prototype.toString.call([]));//返回"[object Array]"
console.log(Object.prototype.toString.call({}));//返回"[object Object]"
console.log(Object.prototype.toString.call("str"));//返回"[object String]"
console.log(Object.prototype.toString.call(true));//返回"[object Boolean]"
console.log(Object.prototype.toString.call(3));//返回"[object Number]"
console.log(Object.prototype.toString.call(null));
//返回"[object Null]" 一般直接判断是否为null
console.log(Object.prototype.toString.call(Undefined));
//返回"[object undefined]"一般直接判断是否为Undefined
网友评论