typeof
typeof会把null会错判为object, 且引用类型都会判断为object如[]会判断为Object而不是具体的Array
typeof 1; // numbertypeof NaN; // numbertypeof '1'; // stringtypeof null; // objecttypeof undefined; // undefinedtypeof Symbol(1); // symboltypeof false; // booleantypeof {}; // objecttypeof []; // objecttypeof new Date(); // objectinstanceof(用于对象类型的判断)
instanceof只能够用于对象类型, 该操作符主要是用来检查构造函数的原型是否在对象的原型链上
1 instanceof Number; // false
NaN instanceof Number; // false
'1' instanceof String; // false
null instanceof null; // Uncaught TypeError: Right-hand side of 'instanceof' is not an object
undefined instanceof undefined; // Uncaught TypeError: Right-hand side of 'instanceof' is not an object
Symbol(1) instanceof Symbol; // false
false instanceof Boolean; // false
({}) instanceof Object; // true
(new Date()) instanceof Date; // true
[] instanceof Array; // true
[] instanceof Object; // constructor
类型的判断还可以直接通过constructor来判断, 但使用constructor并不一定包装类型判断的正确型, 因为对象的constructor可以被任意的修改
[].instructor === Array; // true
{}.instructor === Object; // true
// 修改constructor
function F() {}
function F2() {}
const f = new F();
f.constructor === F; // true
f.constructor = F2;
f.constructor === F; // false
toString
该方法主要是使用Object.prototype.toString()来访问当前值的内部属性[[class]], 该方法在日常中较为常用
Object.prototype.toString.call(null); // '[object Null]'
Object.prototype.toString.call(1); // '[object Number]'
Object.prototype.toString.call('1'); // '[object String]'
Object.prototype.toString.call(undefined); //'[object undefined]'
Object.prototype.toString.call({}); // '[object Object]'
Object.prototype.toString.call(new Date); // '[object Date]'
Object.prototype.toString.call([]); // '[object Array]'
Object.prototype.toString.call(false); // '[object Boolean]'
function getType(val) {
const str = Object.prototype.toString.call(val);
return /^\[Object (.*)\]$/.exec(str)[0]
}