数据类型
- 基本数据类型:
string、number、boolean、undefined、null、Symbol、BigInt - 引用类型:
Object、Array、Function、Date
判断数据类型
-
tyepof: 返回变量数据类型的字符串
typeof "abc"; // 'string' typeof 1; // 'number' typeof true; // 'boolean' typeof undefined; // 'undefined' typeof null; // 'object' typeof Symbol(); // 'symbol' typeof function() {}; // 'function' typeof {}; // 'object' typeof [1, 2]; // 'object' typeof new Date(); // 'object'-
判断基本类型时,除了
null返回'object'外、其他都会返回对应的数据类型字符串; -
判断引用类型时,除了函数返回
function,其他都返回object;
typeof不能区分引用类型,可以使用
instanceOf来判断 -
-
instanceof: 判断构造函数的
prototype是否在指定对象的原型上const obj = {} obj instanceof Object; // true function Person(){} const man = new Person(); man instanceof Person; // true- instanceof返回一个布尔值
- 用来判断引用类型
-
Object.prototype.toString.call()
toString()是 Object 的原型方法,调用时返回对象的[obejct type],其中type是对象的类型;const toString = Object.prototype.toString; toString.call("abc") // '[object String]' toString.call(1); // '[object Number]' toString.call(true); // '[object Boolean]' toString.call(null); // '[object Null]' toString.call(undefined); // '[object Undefined]' toString.call(Symbol()); // '[object Symbol]' toString.call(function() {}); // '[object Function]' toString.call({}); // '[object Object]' toString.call([]); // '[object Array]' toString.call(new Date()); // '[object Date]' toString.call(document); // '[object Document]' toString.call(window); // '[object Window]'