Skip to content

数据类型

类型分类

JavaScript 中的数据类型主要分为两大类:

  • 原始类型(Primitive Types)【7 种】

    1. undefined:表示 未定义 的类型,通常用于变量未赋值的情况。
    2. null:表示 空值 的类型,表示“无”或“空”。
    3. string:表示 文本数据 的类型。如: 'hello'"world"
    4. number:表示 数字 的类型,包括整数和浮点数。如: 423.14
    5. boolean:表示 逻辑值 的类型,只有 truefalse 两个值。如: truefalse
    6. symbol:表示 唯一标识符 的类型。如: Symbol('id')
    7. bigint:表示 大整数 的类型,可以表示比 number 更大的整数。如: 9007199254740991n
  • 引用类型(Reference Types)【1 种】

    如:对象(object)、数组(array)、函数(function)等。

    1. object:表示复杂数据结构的类型,可以包含多个值和属性。如: { name: 'Alice', age: 30 }
    2. array:表示有序列表的类型,可以包含多个值。如: [1, 2, 3]
    3. function:函数即可执行对象,包含一个名为 [[call]] 的内部方法。如: function greet() { console.log('Hello!'); }
    4. ……

判断数据类型

typeof

js
console.log(typeof undefined) // undefined
// 注意,这是 js 语言设计时的历史遗留问题(设计缺陷)
console.log(typeof null) // object
console.log(typeof 'str') // string
console.log(typeof 3.14159) // number
console.log(typeof true) // boolean
console.log(typeof Symbol()) // symbol
console.log(typeof 123n) // bigint
console.log(typeof {}) // object
console.log(typeof []) // object
console.log(typeof function () {}) // function

其中值得注意的是:

  • null 会被判断为 object
  • function 会被判断为 function
  • [] 会被判断为 object

typeof(x)

你可能还会遇到另一种语法:typeof(x)。它与 typeof x 相同。

简单点说:typeof 是一个操作符,不是一个函数。这里的括号不是 typeof 的一部分。它是数学运算分组的括号。

通常,这样的括号里包含的是一个数学表达式,例如 (2 + 2),但这里它只包含一个参数 (x)。从语法上讲,它们允许在 typeof 运算符和其参数之间不打空格,有些人喜欢这样的风格。

instanceof

注意:instanceof 只能判断引用数据类型。

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

js
console.log(true instanceof Boolean) // false
console.log(2 instanceof Number) // false
console.log('str' instanceof String) // false
console.log(Symbol() instanceof Symbol) // false
console.log(123n instanceof BigInt) // false

console.log({} instanceof Object) // true
console.log(function () {} instanceof Function) // true
console.log(function () {} instanceof Object) // true
console.log([] instanceof Array) // true
console.log([] instanceof Object) // true

Object.prototype.toString

js
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
console.log(Object.prototype.toString.call(3.14159)) // [object Number]
console.log(Object.prototype.toString.call('hello')) // [object String]
console.log(Object.prototype.toString.call(Symbol())) // [object Symbol]
console.log(Object.prototype.toString.call(123n)) // [object BigInt]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call(function () {})) // [object Function]
console.log(Object.prototype.toString.call([])) // [object Array]

基于 MIT 许可发布