js 数据类型及 typeof和instanceof 的使用

228 阅读1分钟

最新的 ECMAScript 标准定义了8种数据类型。JavaScript 数据类型和数据结构

基础类型:NumberStringBooleanundefinednullSymbolBigInt

复杂类型:ObjectFunction/Array/Date/RegExp/Math/Set/Map...)

typeof(undefined) === "undefined"
typeof(null) === "object"  //特殊
typeof("") === "string"
typeof(true) === "boolean"
typeof(1) === "number"
typeof(NaN) === "number"  //特殊
typeof(Symbol()) === "symbol"  //ES6新增
typeof(9999n) === "bigint"    // ES2020新增
typeof(Object()) === "object"
typeof(new Object()) === "object"
typeof(Object) === "function"   //注意
typeof(object) === "undefined"  //注意
typeof([]) === "object"
typeof({}) === "object"
typeof(new Array()) === "object"
typeof(new Map()) === "object"
typeof(new Set()) === "object"
typeof(new WeakMap()) === "object"
typeof(new WeakSet()) === "object"
typeof(new Date()) === "object"

记住 typeof 操作符的唯一目的就是检查数据类型,typeof 运算符总是返回字符串,非常确定的只有如下几个:

"undefined","object","boolean","string",
"number","symbol","bigint","function"

如果我们希望检查任何从 Object 派生出来的结构类型,使用 typeof 是不起作用的,因为总是会得到 "object"。检查 Object 种类的合适方式是使用 instanceof 关键字。但即使这样也存在误差。

Object() instanceof Object === true
new Object() instanceof Object === true
new Object() instanceof Function === false  //注意
Object instanceof Function === true    //注意
object instanceof Object  //报错 Uncaught ReferenceError: object is not defined
[] instanceof Array === true
new Array() instanceof Array === true
new Map() instanceof Map === true
new Set() instanceof Set === true
new WeakSet() instanceof WeakSet === true
new WeakMap() instanceof WeakMap === true
new Date() instanceof Date === true

instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的prototype属性。 语法:[对象] instanceof [构造函数]

注意左侧必须是对象(object),如果不是,直接返回false

new String("aa") instanceof String === true
"aa" instanceof String === false  //注意"aa"是基础类型,直接返回false