1.typeof
typeof undefined // 'undefined'
typeof '10' // 'string'
typeof 10 // 'number'
typeof false // 'boolean'
typeof Symbol() // 'symbol'
typeof Function // ‘function'
typeof null // ‘object’
typeof [] // 'object'
typeof {} // 'object'
缺点:
(1)typeof null的结果为object,无法分辨是null还是object
(2)typeof 数组 的结果始终为object
2.instanceof
function Func() { }
var func = new Func();
var n = new Number(1)console.log(func instanceof Func);// true
console.log(n instanceof Number); //true
console.log(12 instanceof Number); //false -->不能判断字面量的基本数据类
缺点:只能判断对象是否存在于目标对象的原型链上,不能判断基本数据类型
3.constructor
var a = 1;
var b = new Number(1);
function func(){console.log("haha");
}
func.prototype = new Array();
var func2 = new func();
var date = new Date();
var arr = [1,2,3];
var reg = /"ex"/gi;console.log(a.constructor); //f Number {[native code]}
console.log(b.constructor); //f Number {[native code]}console.log(func.constructor); //f Function {[native code]}
console.log(func2.constructor) //f Array() {[native code]}console.log(date.constructor); //f Date {[native code]}
console.log(arr.constructor); //f Array {[native code]}
console.log(reg.constructor); //f RegExp {[native code]}
4.Object.prototype.toString.call()
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call(123)); // "[object Number]"
console.log(Object.prototype.toString.call("abc")); // "[object String]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]" function fn() {console.log("ming");
}
var date = new Date();
var arr = [1, 2, 3];
var reg = /[hbc]at/gi;
console.log(Object.prototype.toString.call(fn));// "[object Function]"
console.log(Object.prototype.toString.call(date));// "[object Date]"
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(reg));// "[object RegExp]"
最好的基本类型检测方式 Object.prototype.toString.call() ;它可以区分 null 、 string
boolean 、 number 、 undefined 、 array 、 function 、 object 、 date 、 math 数据类型
更多推荐
四种,数据类型,方法
发布评论