对象类型
本章将详细介绍ECMAScript中的各种内置对象类型,包括Array、Date、RegExp、Error等,以及ES6引入的Map、Set等新对象类型,帮助您掌握这些重要对象的使用方法。
12.1 Array对象
Array对象用于存储有序的元素集合,是JavaScript中最常用的数据结构之一。
数组创建
// 数组字面量
let arr1 = [1, 2, 3];
// Array构造函数
let arr2 = new Array(1, 2, 3);
let arr3 = new Array(5); // 创建长度为5的空数组
// Array.of() (ES6)
let arr4 = Array.of(1, 2, 3); // [1, 2, 3]
let arr5 = Array.of(5); // [5] (不是长度为5的数组)
// Array.from() (ES6)
let arr6 = Array.from("hello"); // ['h', 'e', 'l', 'l', 'o']
let arr7 = Array.from({length: 3}, (v, i) => i); // [0, 1, 2]
数组方法
let fruits = ["苹果", "香蕉", "橙子"];
// 栈方法
fruits.push("葡萄"); // 添加到末尾
let last = fruits.pop(); // 移除并返回最后一个元素
// 队列方法
fruits.unshift("草莓"); // 添加到开头
let first = fruits.shift(); // 移除并返回第一个元素
// 操作方法
let removed = fruits.splice(1, 1, "芒果"); // 在索引1处删除1个元素,添加"芒果"
// 转换方法
let str = fruits.join(", "); // "苹果, 芒果, 橙子"
// 迭代方法
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// 映射方法
let upperFruits = fruits.map(fruit => fruit.toUpperCase());
// 过滤方法
let longNames = fruits.filter(fruit => fruit.length > 2);
// 归约方法
let totalLength = fruits.reduce((total, fruit) => total + fruit.length, 0);
ES6数组新方法
let numbers = [1, 2, 3, 4, 5];
// find和findIndex
let found = numbers.find(n => n > 3); // 4
let index = numbers.findIndex(n => n > 3); // 3
// includes (ES2016)
console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false
// flat (ES2019)
let nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]
12.2 Date对象
Date对象用于处理日期和时间。
Date创建
// 当前日期和时间
let now = new Date();
// 指定日期时间
let specific = new Date(2025, 9, 11); // 2025年10月11日 (月份从0开始)
let withTime = new Date(2025, 9, 11, 14, 30, 0); // 2025年10月11日 14:30:00
// 从字符串创建
let fromString = new Date("2025-10-11");
let fromISOString = new Date("2025-10-11T14:30:00Z");
// 从时间戳创建
let fromTimestamp = new Date(1728645000000);
Date方法
let date = new Date(2025, 9, 11, 14, 30, 45);
// 获取方法
console.log(date.getFullYear()); // 2025
console.log(date.getMonth()); // 9 (0-11)
console.log(date.getDate()); // 11 (1-31)
console.log(date.getHours()); // 14
console.log(date.getMinutes()); // 30
console.log(date.getSeconds()); // 45
// 设置方法
date.setFullYear(2026);
date.setMonth(11); // 12月
date.setDate(25);
// 格式化方法
console.log(date.toString()); // "Fri Dec 25 2026 14:30:45 GMT+0800"
console.log(date.toISOString()); // "2026-12-25T06:30:45.000Z"
console.log(date.toLocaleDateString()); // "2026/12/25"
console.log(date.toLocaleTimeString()); // "14:30:45"
12.3 RegExp对象
RegExp对象用于处理正则表达式。
RegExp创建
// 字面量语法
let regex1 = /hello/i; // i标志表示忽略大小写
// 构造函数
let regex2 = new RegExp("hello", "i");
// 转义特殊字符
let regex3 = new RegExp("\\d+"); // 匹配数字
RegExp方法
let text = "Hello World, hello JavaScript";
let regex = /hello/gi;
// test方法
console.log(regex.test(text)); // true
// exec方法
let result = regex.exec(text);
console.log(result); // ["Hello", index: 0, input: "...", groups: undefined]
// 字符串的正则方法
console.log(text.match(regex)); // ["Hello", "hello"]
console.log(text.search(regex)); // 0
console.log(text.replace(regex, "hi")); // "hi World, hi JavaScript"
console.log(text.split(/\s+/)); // ["Hello", "World,", "hello", "JavaScript"]
12.4 Error对象
Error对象用于表示运行时错误。
Error类型
// 基本Error
let error = new Error("发生了一个错误");
console.log(error.message); // "发生了一个错误"
console.log(error.name); // "Error"
// 特定类型的错误
let syntaxError = new SyntaxError("语法错误");
let typeError = new TypeError("类型错误");
let referenceError = new ReferenceError("引用错误");
let rangeError = new RangeError("范围错误");
// 自定义错误
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
try {
throw new CustomError("这是一个自定义错误");
} catch (error) {
console.log(error.name); // "CustomError"
console.log(error.message); // "这是一个自定义错误"
}
12.5 Map对象 (ES6)
Map对象保存键值对,任何值都可以作为键或值。
Map基本操作
// 创建Map
let map = new Map();
// 设置键值对
map.set("name", "张三");
map.set(1, "数字键");
map.set(true, "布尔键");
// 获取值
console.log(map.get("name")); // "张三"
console.log(map.get(1)); // "数字键"
// 检查是否存在
console.log(map.has("name")); // true
// 删除键值对
map.delete("name");
console.log(map.has("name")); // false
// 获取大小
console.log(map.size); // 2
// 清空Map
map.clear();
console.log(map.size); // 0
Map遍历
let map = new Map([
["name", "张三"],
["age", 25],
["city", "北京"]
]);
// forEach遍历
map.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// for...of遍历
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
// 获取键、值、键值对
console.log([...map.keys()]); // ["name", "age", "city"]
console.log([...map.values()]); // ["张三", 25, "北京"]
console.log([...map.entries()]); // [["name", "张三"], ["age", 25], ["city", "北京"]]
12.6 Set对象 (ES6)
Set对象存储唯一的值,可以是任何类型的值。
Set基本操作
// 创建Set
let set = new Set();
// 添加值
set.add("apple");
set.add("banana");
set.add("orange");
set.add("apple"); // 重复值会被忽略
// 检查是否存在
console.log(set.has("apple")); // true
console.log(set.has("grape")); // false
// 删除值
set.delete("banana");
console.log(set.has("banana")); // false
// 获取大小
console.log(set.size); // 2
// 清空Set
set.clear();
console.log(set.size); // 0
Set遍历
let set = new Set(["apple", "banana", "orange"]);
// forEach遍历
set.forEach(value => {
console.log(value);
});
// for...of遍历
for (let value of set) {
console.log(value);
}
// 转换为数组
let array = [...set];
console.log(array); // ["apple", "banana", "orange"]
Set应用示例
// 数组去重
let numbers = [1, 2, 2, 3, 3, 4, 5, 5];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
// 集合运算
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([3, 4, 5, 6]);
// 交集
let intersection = new Set([...setA].filter(x => setB.has(x)));
console.log([...intersection]); // [3, 4]
// 并集
let union = new Set([...setA, ...setB]);
console.log([...union]); // [1, 2, 3, 4, 5, 6]
// 差集
let difference = new Set([...setA].filter(x => !setB.has(x)));
console.log([...difference]); // [1, 2]
12.7 WeakMap和WeakSet (ES6)
WeakMap和WeakSet是弱引用版本的Map和Set。
WeakMap
// WeakMap只接受对象作为键
let weakMap = new WeakMap();
let obj1 = {};
let obj2 = {};
weakMap.set(obj1, "值1");
weakMap.set(obj2, "值2");
console.log(weakMap.get(obj1)); // "值1"
// 当对象没有其他引用时,WeakMap中的条目会被自动清除
obj1 = null; // obj1的引用被清除
WeakSet
// WeakSet只存储对象
let weakSet = new WeakSet();
let obj1 = {};
let obj2 = {};
weakSet.add(obj1);
weakSet.add(obj2);
console.log(weakSet.has(obj1)); // true
// 当对象没有其他引用时,WeakSet中的条目会被自动清除
obj1 = null; // obj1的引用被清除
12.8 Promise对象 (ES6)
Promise对象用于处理异步操作。
Promise基本用法
// 创建Promise
let promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
let success = Math.random() > 0.5;
if (success) {
resolve("操作成功");
} else {
reject("操作失败");
}
}, 1000);
});
// 处理Promise结果
promise
.then(result => {
console.log("成功:", result);
})
.catch(error => {
console.log("失败:", error);
})
.finally(() => {
console.log("操作完成");
});
Promise静态方法
// Promise.resolve()
let resolvedPromise = Promise.resolve("成功");
// Promise.reject()
let rejectedPromise = Promise.reject("失败");
// Promise.all()
let promise1 = Promise.resolve(1);
let promise2 = Promise.resolve(2);
let promise3 = Promise.resolve(3);
Promise.all([promise1, promise2, promise3])
.then(results => {
console.log(results); // [1, 2, 3]
});
// Promise.race()
Promise.race([promise1, promise2, promise3])
.then(result => {
console.log(result); // 1 (第一个完成的Promise的结果)
});
12.9 其他内置对象
JSON对象
// JSON序列化
let obj = {name: "张三", age: 25};
let jsonStr = JSON.stringify(obj);
console.log(jsonStr); // '{"name":"张三","age":25}'
// JSON解析
let parsedObj = JSON.parse(jsonStr);
console.log(parsedObj.name); // "张三"
// 格式化输出
let formatted = JSON.stringify(obj, null, 2);
console.log(formatted);
/*
{
"name": "张三",
"age": 25
}
*/
Math对象
// 数学常量
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045
// 基本数学函数
console.log(Math.abs(-5)); // 5
console.log(Math.ceil(4.2)); // 5
console.log(Math.floor(4.8)); // 4
console.log(Math.round(4.5)); // 5
// 幂和根
console.log(Math.pow(2, 3)); // 8
console.log(Math.sqrt(16)); // 4
// 随机数
console.log(Math.random()); // 0到1之间的随机数
提示:理解各种内置对象类型的特性和使用方法对于JavaScript开发至关重要。不同对象类型适用于不同的场景,选择合适的对象类型可以提高代码效率和可读性。