JavaScript核心内置对象深度解析:Object、Array、Date与RegExp
JavaScript 引用类型核心指南
在 JavaScript 编程中,引用类型构成了处理复杂数据的基石。不同于基本类型,引用类型能够存储多个值或更复杂的实体。本文将深入探讨四个最核心的内置对象:Object(对象)、Array(数组)、Date(日期)和RegExp(正则表达式),并通过重构后的代码示例展示其在实际开发中的应用。
一、Object:动态的数据集合
Object 是 JavaScript 中所有引用类型的基础。本质上,它是一个无序的键值对集合,允许开发者动态地添加、修改或删除属性。这种灵活性使其成为存储数据和封装逻辑的理想容器。
示例:构建动态配置对象
// 使用字面量语法创建配置对象
const appConfig = {
apiUrl: 'https://api.example.com/v1',
timeout: 5000,
isAuthenticated: false,
login: function() {
this.isAuthenticated = true;
console.log(`已连接至 ${this.apiUrl}`);
}
};
appConfig.login(); // 输出: 已连接至 https://api.example.com/v1
// 使用构造函数创建并动态赋值
const userProfile = new Object();
userProfile.userId = 1001;
userProfile.roles = ['admin', 'editor'];
// 添加计算属性
Object.defineProperty(userProfile, 'accessLevel', {
get() {
return this.roles.includes('admin') ? 'High' : 'Low';
}
});
console.log(userProfile.accessLevel); // 输出: "High"
二、Array:有序的线性数据结构
数组是专门用于存储有序数值集合的对象。与普通对象不同,数组使用数字索引(从 0 开始)来访问元素,并提供了丰富的操作方法(如迭代、映射、过滤)来处理数据流。
示例:库存数据处理
// 初始化库存列表
const stockItems = [
{ id: 'A1', quantity: 15, price: 100 },
{ id: 'B2', quantity: 5, price: 200 },
{ id: 'C3', quantity: 50, price: 50 }
];
// 1. 使用 filter 筛选库存不足的商品
const lowStock = stockItems.filter(item => item.quantity < 10);
// 结果: [{ id: 'B2', quantity: 5, price: 200 }]
// 2. 使用 map 计算每项商品的总价值
const itemValues = stockItems.map(item => ({
id: item.id,
totalValue: item.quantity * item.price
}));
// 3. 使用 reduce 计算库存总价值
const grandTotal = stockItems.reduce((sum, item) => {
return sum + (item.quantity * item.price);
}, 0);
console.log(`库存总价值: ${grandTotal}`); // 输出计算结果
三、Date:时间戳与日期运算
Date 对象基于 UTC 时间 1970 年 1 月 1 日开始的毫秒数来处理时间。它不仅可以获取当前的系统时间,还能执行复杂的日期计算、格式化以及时区转换。
示例:会员到期倒计时
// 获取当前时间
const now = new Date();
// 设定会员过期时间 (注意:月份是从0开始计数,11代表12月)
const expirationDate = new Date(2024, 11, 31, 23, 59, 59);
// 计算时间差(毫秒)
const timeDiff = expirationDate.getTime() - now.getTime();
// 将毫秒转换为天数
const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
if (daysRemaining > 0) {
console.log(`会员还有 ${daysRemaining} 天到期`);
} else {
console.log('会员已过期');
}
// 获取具体的日期组成部分
const year = expirationDate.getFullYear();
const month = expirationDate.toLocaleString('default', { month: 'long' });
console.log(`过期时间:${year}年${month}`);
四、RegExp:强大的模式匹配工具
正则表达式(RegExp)提供了一种高效的方式来搜索、匹配和替换字符串中的特定模式。它是处理文本验证、数据提取和格式清洗的利器。
示例:敏感信息过滤与验证
// 定义正则模式:匹配手机号码 (简化版)
const phoneRegex = /1[3-9]\d{9}/;
// 验证输入
const userInput = "13812345678";
console.log(phoneRegex.test(userInput)); // 输出: true
// 定义模式:从日志中提取十六进制颜色代码
const logData = "Error: color #ff0000 not found, trying #00ff00.";
const hexRegex = /#([a-fA-F0-9]{6})/g;
// 使用 matchAll 进行迭代提取
const matches = logData.matchAll(hexRegex);
const foundColors = [];
for (const match of matches) {
foundColors.push(match[0]);
}
console.log(`发现颜色代码: ${foundColors.join(', ')}`);
// 输出: 发现颜色代码: #ff0000, #00ff00
// 替换敏感词
const textBlock = "用户密码是:123456,请勿泄露。";
const sanitized = textBlock.replace(/\d{6}/g, "******");
console.log(sanitized);
// 输出: 用户密码是:******,请勿泄露。