最新的 ECMAScript 标准定义了 8 种数据类型:
-
7 种原始类型:
Boolean
Null
Undefined
Number
BigInt
String
Symbol -
引用类型:Object
JavaScript 中的类型判断方式有很多种,接下来就让我们来盘点一下。
一、typeof
typeof是比较常用的一种判断方式,使用方式也比较简单,如:
number:
typeof 1; // "number"
string:
typeof 'hello'; // "string"
boolean:
typeof true; // "boolean"
undefined:
typeof undefined; // "undefined"
null:
typeof null; // "undefined" (特别)
object:
typeof {}; // "object"
Symbol:
typeof Symbol(); // "symbol"
但是用 typeof 来进行类型判断有以下几个问题:
1、typeof null === "object"(JS历史遗留问题)
2、JS 里有许多内置的构造函数, 因此对象又可以分为许多类型: array function date regexp 等等, 但是 typeof 只能显示出 "function" 这一种类型的对象, 也就是说, 除了 function, 其他类型的对象都会被当做 "object"。
typeof [] ; //object
typeof new Date(); //object
typeof new RegExp(); //object
二、instanceof
用法: instanceof 是用来判断 A 是否为 B 的实例。
instanceof 检测的是原型,也就是是用A.proto 是否等于 B.prototype 来判断对象的类型的。
String:
var str = new String('hello');
str instanceof String // true
var str = new Number('10');
str instanceof String // true
Date:
var date = new Date();
date instanceof Date; // true
Array:
var arr = new Array();
arr instanceof Array; // true
RegExp:
var reg = new RegExp('/^[a-z]$/');
reg instanceof RegExp; // true
Object:
var obj = {};
obj instanceof Object; // true
Function:
var o = function() {};
o instanceof Function; // true
注意:他们本身就是对象
var str = new String('hello');
str instanceof Object // true
var date = new Date();
date instanceof Object; // true
...
三、Object.prototype.toString.call()
toString() 是 Object 的原型上的方法。为什么不用 obj.toString() 呢?
因为 Function.prototype, Array.prototype 等这些原型上都重写了 toString 方法, 为了保证输出结果的形式统一, 借用最纯净的 Object 原型上的方法。
Object.prototype.toString.call('h'); // "[object String]"
Object.prototype.toString.call(1); // "[object Number]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(); // "[object Undefined]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call(new Date()); // "[object Date]"
Object.prototype.toString.call(/^[a-z]$/); // "[object RegExpArray]"
Object.prototype.toString.call(function () {}); // "[object Function]"
四、constructor
一个实例对象上会有一个constructor属性,指向他的构造函数。我们可以利用这个特点来得到她的数据类型。
''.constructor == String //true
new Number(1).constructor == Number //true
new Date().constructor == Date //true
true.constructor == Boolean //true
[].constructor == Array //true
(()=>{}).constructor == Function //true
如果您觉得我的文章有用,欢迎点赞和关注,也欢迎光临我的个人博客 github.com/BokFang