JS判断数据类型

JS有6中基本数据类型+Object类型+Fuction类型

  • undefined
  • Null
  • Boolean
  • Number
  • String
  • Symbol(在es10中加入了第7种原始类型BigInt,现已被最新Chrome支持)其中Symbol是ES6新增的

还有一种复杂类型(引用类型)Object和函数类型Function。我们常用typeof和instanceof操作符来判断数据类型

typeof和instanceof的区别

  • typeof返回变量的基本类型,instanceof返回的是一个布尔值
  • typeof只能准确判断基本类型(null除外),无法判断引用类型(function除外),对于 Array, Null 等特殊对象返回 object。
  • instanceof 可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型
// Numbers 
typeof 37 === 'number';
// Strings 
typeof "" === 'string';
// Booleans 
typeof true === 'boolean';
// Symbols 
typeof Symbol('foo') === 'symbol';
// Undefined 
typeof undefined === 'undefined'; 
typeof blabla === 'undefined'; // 一个未定义的变量,或者一个定义了却未赋初值的变量
// Objects 
typeof {a:1} === 'object';
type [1,2,3] = 'object'
------------------------'下面是不是有点奇怪?'--------------------------
// 函数
typeof function(){} === 'function';
// Null
typeof null === 'object'

Object.prototype.toString.call(xx)

Object.prototype.toString.call(null);       // => "[object Null]"

Object.prototype.toString.call(undefined);  // => "[object Undefined]"

// Boolean 类型,tag 为 "Boolean"
Object.prototype.toString.call(true);            // => "[object Boolean]"

// Number 类型,tag 为 "Number"
Object.prototype.toString.call(1);               // => "[object Number]"

// String 类型,tag 为 "String"
Object.prototype.toString.call("");              // => "[object String]"

// Array 类型,tag 为 "Object"
Object.prototype.toString.call({});              // => "[object Object]"

// Array 类型,tag 为 "Array"
Object.prototype.toString.call([]);              // => "[object Array]"

// Arguments 类型,tag 为 "Arguments"
Object.prototype.toString.call((function() {
  return arguments;
})());                                           // => "[object Arguments]"

// Function 类型, tag 为 "Function"
Object.prototype.toString.call(function(){});    // => "[object Function]"

// Error 类型(包含子类型),tag 为 "Error"
Object.prototype.toString.call(new Error());     // => "[object Error]"

// RegExp 类型,tag 为 "RegExp"
Object.prototype.toString.call(/\d+/);           // => "[object RegExp]"

// Date 类型,tag 为 "Date"
Object.prototype.toString.call(new Date());      // => "[object Date]"

// 其他类型,tag 为 "Object"
Object.prototype.toString.call(new class {});    // => "[object Object]"