前端JS: 数据类型

5 阅读2分钟

JavaScript 数据类型详解

一、数据类型分类

1. 基本数据类型(Primitive Types)

  • String​ - 字符串
  • Number​ - 数字
  • Boolean​ - 布尔值
  • Null​ - 空值
  • Undefined​ - 未定义
  • Symbol​ (ES6+) - 唯一值
  • BigInt​ (ES2020+) - 大整数

2. 引用数据类型(Reference Types)

  • Object​ - 对象

    • Array - 数组
    • Function - 函数
    • Date - 日期
    • RegExp - 正则表达式
    • Map/Set (ES6+) - 集合结构

二、数据类型特点

基本数据类型

// 存储在栈内存
let a = 10;
let b = a;  // 创建副本
b = 20;
console.log(a);  // 10 (a不变)

引用数据类型

// 存储在堆内存,栈中存储引用地址
let obj1 = { name: 'Tom' };
let obj2 = obj1;  // 复制引用地址
obj2.name = 'Jerry';
console.log(obj1.name);  // 'Jerry' (obj1也改变)

三、类型检测方法

1. typeof

typeof 'hello'     // 'string'
typeof 42         // 'number'
typeof true       // 'boolean'
typeof undefined  // 'undefined'
typeof null       // 'object' (历史遗留问题)
typeof []         // 'object'
typeof {}         // 'object'
typeof function(){} // 'function'
typeof Symbol()   // 'symbol'
typeof 10n        // 'bigint'

2. instanceof

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

3. Object.prototype.toString

Object.prototype.toString.call([])      // '[object Array]'
Object.prototype.toString.call({})      // '[object Object]'
Object.prototype.toString.call(null)    // '[object Null]'
Object.prototype.toString.call(undefined) // '[object Undefined]'

4. Array.isArray

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

四、类型转换

1. 显式转换

// 转数字
Number('123')     // 123
Number('123abc')  // NaN
parseInt('123.5') // 123
parseFloat('123.5') // 123.5

// 转字符串
String(123)      // '123'
(123).toString() // '123'

// 转布尔
Boolean(1)       // true
Boolean(0)       // false

2. 隐式转换

// 字符串连接
'5' + 3          // '53'
'5' - 3          // 2

// 比较运算
'5' == 5         // true
'5' === 5        // false

// 布尔转换
if (0) { ... }   // false
if ('hello') { ... } // true

五、面试常见问题

1. 判断数据类型最优方案

function getType(value) {
  return Object.prototype.toString.call(value)
    .slice(8, -1)
    .toLowerCase();
}

2. null vs undefined

  • null: 表示空值,手动设置
  • undefined: 表示未定义,系统默认
  • typeof null === 'object' 是历史遗留bug

3. Symbol特点

  • 唯一性,不会重复
  • 可以作为对象的唯一key
  • 不参与for...in遍历

4. 类型转换规则总结

// 转数字规则
+ ''       // 0
+ '123'    // 123
+ 'abc'    // NaN
+ true     // 1
+ false    // 0
+ null     // 0
+ undefined // NaN