typeof

Typeof will misjudge null as object and reference types as object. For example, [] will judge object instead of Array

typeof 1; // numbertypeof NaN; // numbertypeof '1'; // stringtypeof null; // objecttypeof undefined; // undefinedtypeof Symbol(1); // symboltypeof false; // booleantypeof {}; // objecttypeof []; // objecttypeof new Date(); // objectCopy the code

Instanceof (for object type determination)

Instanceof can only be used for object types. The main purpose of this operator is to check whether the stereotype of the constructor is on the stereotype chain of the object

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; // Copy the code

constructor

Type judgment can also be made directly from constructor, but using constructor does not necessarily wrap up the correct type of type judgment, since the object’s constructor can be modified arbitrarily

[].instructor === Array; // true
{}.instructor === Object; // true

/ / modify the constructor
function F() {}
function F2() {}
const f = new F();
f.constructor === F; // true
f.constructor = F2;
f.constructor === F; // false
Copy the code

toString

The method mainly use the Object. The prototype. The toString () to access the internal properties of the current value [[class]], the method is relatively common in the everyday

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]}Copy the code