typeof {} // object typeof [1,2] // object typeof /\s/ //object
原理 因为A instanceof B 可以判断A是不是B的实例,返回一个布尔值,由构造类型判断出数据类型
console.log(arr instanceof Array ); // true console.log(date instanceof Date ); // true console.log(fn instanceof Function ); // true //注意: instanceof 后面一定要是对象类型,大小写不能写错,该方法试用一些条件选择或分支
Object.prototype.toString.call(); console.log(toString.call(123)); //[object Number] console.log(toString.call(‘123‘)); //[object String] console.log(toString.call(undefined)); //[object Undefined] console.log(toString.call(true)); //[object Boolean] console.log(toString.call({})); //[object Object] console.log(toString.call([])); //[object Array] console.log(toString.call(function(){})); //[object Function]
console.log(‘数据类型判断‘ - constructor); console.log(arr.constructor === Array); //true console.log(date.constructor === Date); //true console.log(fn.constructor === Function); //true
原文:https://www.cnblogs.com/passkey/p/12757589.html