js 类型判断
1.typeof
其他(数字Number,布尔值Boolean,字符串String,函数Function,对象Object,Undefined)这一些数据类型在typeof 下都被精准的解释,只有数组和null的数据类型不够精准。
console.log(typeof 2); // number console.log(typeof true); // boolean console.log(typeof 'str'); // string console.log(typeof []); // object []数组的数据类型在 typeof 中被解释为 console.log(typeof function(){}); // function console.log(typeof {}); // object console.log(typeof undefined); // undefined console.log(typeof null);
2.instanceof
只有引用数据类型(Array,Function,Object)被精准判断
console.log(2 instanceof Number); // false console.log(true instanceof Boolean); // false console.log('str' instanceof String); // false console.log([] instanceof Array); // true console.log(function(){} instanceof Function); // true console.log({} instanceof Object);
3.constructor
console.log((2).constructor === Number); console.log((true).constructor === Boolean); console.log(('str').constructor === String); console.log(([]).constructor === Array); console.log((function() {}).constructor === Function); console.log(({}).constructor === Object);
4.Object.prototype.toString.call
最靠谱
var a = Object.prototype.toString; console.log(a.call(2)); console.log(a.call(true)); console.log(a.call('str')); console.log(a.call([])); console.log(a.call(function(){})); console.log(a.call({})); console.log(a.call(undefined)); console.log(a.call(null));
参考 :https://blog.csdn.net/zjy_android_blog/article/details/81023177