js类型详解 发表于 2018-10-24 js中获取变量类型 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263// js 中类型type: // Number Boolean String Function Array Date RegExp Null Undefined Object// 使用typeoflet arr = [1, 2, 3];// typeof 的缺点就是 会把Array和Date和RexExp和null判断为objectconsole.log('1', typeof arr); // object function xixi() {}console.log('2', typeof xixi); // functionlet obj = {};console.log('3', typeof obj); // object// 使用constructor 或者constructor.nameconsole.log('44', arr.constructor) // Arrayconsole.log('4', arr.constructor.name === 'Array') // trueconsole.log('5', typeof arr.constructor); // functionclass Hello {}console.log('6', typeof Hello); // functionlet hello = new Hello();console.log('7', typeof hello); // objectconsole.log('8', hello.constructor.name) // Hello// 使用 instanceof判断console.log('9', arr instanceof Array); // trueconsole.log('10', (typeof arr === 'object') && (arr.constructor.name === 'Array')); // true// 原型判断console.log('11', Object.prototype.toString.call(arr)) // [object Array]function type(obj) { let class2type = {}; let objs = "Boolean Number String Function Array Date RegExp Null Undefined".split(" "); objs.forEach(obj => { class2type[`[object ${obj}]`] = obj.toLocaleLowerCase(); }); return class2type[Object.prototype.toString.call(obj)] || 'object';}console.log(type(arr)); // arrayconsole.log(type(hello)); // objectlet u;console.log(u); // undefinedconsole.log(null); // nullconsole.log(Object.prototype.toString.call(null)); // [object Null]console.log(typeof null) // object 这个js的一个缺陷。console.log(typeof u); // undefinedconsole.log(Object.prototype.toString.call(arr)); // [object Array]console.log(Object.prototype.toString.call(hello)); // [object Object]console.log(Object.prototype.toString.call(xixi)) // [object Function]console.log(Object.prototype.toString.call(hello.constructor)) // [object Function]let reg = /^\s*|\s*^/g;console.log(Object.prototype.toString.call(reg)); // [object RegExp]console.log(typeof reg) // objectconsole.log(typeof 12); // numberconsole.log(typeof new Date()) // object