一、typeof
console.log(typeof 123); // number
console.log(typeof '123'); // string
console.log(typeof true); // boolean
console.log(typeof null); // object
console.log(typeof undefinde); // undefined
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof function fn(){}); // function
通过上面的监测,我们可以看出 typeof 检测 Array 以及 Object 返回的类型都是 object,因此用 typeof 是无法检测出数组和对象的
二、instanceof
var obj = {}, arr = [];
console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true
注意:instanceof 只可以用来判断数组和对象;
由于数组也属于对象因此我们使用 instanceof 判断一个数组是否为对象结果也会是 true
console.log(arr instanceof Object); // true
可以封装一个方法改进:
function getDAtaType(e){
if(e instanceof Array) {
return 'Array'
} else if(e instanceof Object) {
return 'Object'
} else {
return 'data is no object type'
}
}
三、constructor
var obj = {}, arr = [], n = null, u = undefined, f = function fn(){}, num = 123, str = '123', b = true;
console.log(obj.constructor === Object) // true
console.log(arr.constructor === Array) // true
console.log(n.constructor) // Cannot read property 'constructor' of null
console.log(u.constructor) // Cannot read property 'constructor' of null
console.log(f.constructor === Function) // true
console.log(num.constructor === Number) // true
console.log(str.constructor === String) // true
console.log(b.constructor === Boolean) // true
四、Object.prototype.toString.call()-最佳方案
var obj = {}, arr = [], n = null, u = undefined, f = function fn(){}, num = 123, str = '123', b = true;
console.log(Object.prototype.toString.call(obj)); // [object Object]
console.log(Object.prototype.toString.call(arr)); // [object Array]
console.log(Object.prototype.toString.call(n)); // [object Null]
console.log(Object.prototype.toString.call(u)); // [object Undefined]
console.log(Object.prototype.toString.call(f)); // [object Function]
console.log(Object.prototype.toString.call(num)); // [object Number]
console.log(Object.prototype.toString.call(str)); // [object String]
console.log(Object.prototype.toString.call(b)); // [object Boolean]
想了解js基本数据类型的童鞋看这里:https://www.jianshu.com/p/9d0a14d19fab