JS数据类型

103 阅读1分钟

JavaScript的数据类型

基本类型

Number(数字)

  • 特殊值:Infinity、-Infinity、NaN

String字符串 Boolean布尔值 Undefined 未定义 Null 空值 BigInt 大整数:表示大于2^53-1的整数

  • 字面量法:在数字后加n const bigInt = 123n;
  • 构造函数法 const a = BigInt("1224")

Symbol 符号:唯一且不可变的值,常用作对象属性的键

引用类型

Object Array Function Date RegExp Set Map WeakSet/WeakMap 其他内置对象

  • Error Promise Proxy ArrayBuffer

判断数据类型的方法

typeof 操作符

适用场景:快速判断基本数据类型(null除外)

typeof null       // "object" (历史遗留问题)
typeof function(){} // "function"
typeof Symbol()  // "symbol"
typeof BigInt("123")  // "bigint"

instanceof

适用场景:判断对象是否是某个类的实例

[] instanceof Array      // true
{} instanceof Object     // true
new Date() instanceof Date // true
"hello" instanceof String // false (原始类型)

Object.prototype.toString.call()

特点​:

  • 最准确的类型判断方法
  • 可以识别所有内置类型
  • 返回格式为 [object Type]
Object.prototype.toString.call("hello")  // "[object String]"
Object.prototype.toString.call(123)      // "[object Number]"
Object.prototype.toString.call(null)     // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call([])       // "[object Array]"
Object.prototype.toString.call({})       // "[object Object]"
Object.prototype.toString.call(new Date()) // "[object Date]"

Array.isArray()

适用场景​:专门判断数组类型

Array.isArray([])    // true
Array.isArray({})    // false

最佳实践建议

  1. 基本数据类型​:使用 typeof(注意 null 特殊情况)
  2. 数组检测​:优先使用 Array.isArray()
  3. 精确类型判断​:使用 Object.prototype.toString.call()
  4. 自定义对象​:使用 instanceof 检查实例关系
  5. 避免使用​:constructor(除非确定不会被修改)

特殊案例处理

// 判断 null
function isNull(value) {
  return value === null;
}

// 判断 NaN
function isNaN(value) {
  return Number.isNaN(value); // 或者 value !== value
}

// 判断普通对象 (非数组、日期等)
function isPlainObject(obj) {
  return Object.prototype.toString.call(obj) === '[object Object]' &&
    (obj.constructor === Object || Object.getPrototypeOf(obj) === Object.prototype);
}