TypeScript 集合类型语法知识点及案例代码
TypeScript 提供了多种集合类型,用于存储和管理数据。以下将详细介绍 数组(Array)、元组(Tuple)、集合(Set) 和 映射(Map),包括其语法、常用操作及案例代码。
1. 数组(Array)
1.1 创建数组对象
在 TypeScript 中,数组可以通过以下几种方式创建:
-
使用方括号语法
let fruits: string[] = ['Apple', 'Banana', 'Cherry']; let numbers: number[] = [1, 2, 3, 4, 5]; -
使用泛型语法
let fruits: Array<string> = ['Apple', 'Banana', 'Cherry']; let numbers: Array<number> = [1, 2, 3, 4, 5]; -
使用
Array构造函数let fruits: string[] = new Array('Apple', 'Banana', 'Cherry'); let numbers: number[] = new Array(1, 2, 3, 4, 5);
1.2 Array 类常用函数和属性
-
属性
-
length: 返回数组的长度。let arr: number[] = [1, 2, 3]; console.log(arr.length); // 输出: 3
-
-
方法
-
push(item: T): 向数组末尾添加一个元素。let arr: number[] = [1, 2, 3]; arr.push(4); console.log(arr); // 输出: [1, 2, 3, 4] -
pop(): 移除并返回数组的最后一个元素。let arr: number[] = [1, 2, 3]; let last = arr.pop(); console.log(last); // 输出: 3 console.log(arr); // 输出: [1, 2] -
shift(): 移除并返回数组的第一个元素。let arr: number[] = [1, 2, 3]; let first = arr.shift(); console.log(first); // 输出: 1 console.log(arr); // 输出: [2, 3] -
unshift(item: T): 向数组开头添加一个元素。let arr: number[] = [1, 2, 3]; arr.unshift(0); console.log(arr); // 输出: [0, 1, 2, 3] -
splice(start: number, deleteCount?: number, ...items: T[]): 更改数组内容。let arr: number[] = [1, 2, 3, 4, 5]; arr.splice(2, 1, 6); // 从索引2开始,删除1个元素,插入6 console.log(arr); // 输出: [1, 2, 6, 4, 5] -
slice(begin?: number, end?: number): 返回数组的一个片段。let arr: number[] = [1, 2, 3, 4, 5]; let sliced = arr.slice(1, 3); console.log(sliced); // 输出: [2, 3] -
forEach(callback: (value: T, index: number, array: T[]) => void): 对数组的每个元素执行指定的操作。let arr: number[] = [1, 2, 3]; arr.forEach((value, index) => {console.log(`Index ${index}: ${value}`); }); // 输出: // Index 0: 1 // Index 1: 2 // Index 2: 3 -
map<U>(callback: (value: T, index: number, array: T[]) => U): 对数组的每个元素执行指定的操作,并返回一个新数组。let arr: number[] = [1, 2, 3]; let doubled = arr.map(value => value * 2); console.log(doubled); // 输出: [2, 4, 6] -
filter(callback: (value: T, index: number, array: T[]) => boolean): 过滤数组,返回符合条件的元素组成的新数组。let arr: number[] = [1, 2, 3, 4, 5]; let even = arr.filter(value => value % 2 === 0); console.log(even); // 输出: [2, 4]
-
2. 元组(Tuple)
2.1 定义元组和赋值
元组是固定长度和固定类型的数组。
// 定义一个包含字符串和数字的元组
let person: [string, number] = ['Alice', 30];// 赋值
person = ['Bob', 25];
2.2 元组常用操作
-
访问元素
let person: [string, number] = ['Alice', 30]; console.log(person[0]); // 输出: 'Alice' console.log(person[1]); // 输出: 30 -
解构赋值
let person: [string, number] = ['Alice', 30]; let [name, age] = person; console.log(name); // 输出: 'Alice' console.log(age); // 输出: 30 -
添加元素
let person: [string, number] = ['Alice', 30]; person.push(28); console.log(person); // 输出: ['Alice', 30, 28] -
遍历元组
let person: [string, number] = ['Alice', 30]; person.forEach((value, index) => {console.log(`Index ${index}: ${value}`); }); // 输出: // Index 0: Alice // Index 1: 30 -
长度属性
let person: [string, number] = ['Alice', 30]; console.log(person.length); // 输出: 2
3. 集合(Set)
3.1 创建 Set 对象
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
3.2 Set 类常用操作
-
添加元素
let fruits: Set<string> = new Set(['Apple', 'Banana']); fruits.add('Cherry'); console.log(fruits); // 输出: Set { 'Apple', 'Banana', 'Cherry' } -
删除元素
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); fruits.delete('Banana'); console.log(fruits); // 输出: Set { 'Apple', 'Cherry' } -
检查元素是否存在
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); console.log(fruits.has('Apple')); // 输出: true console.log(fruits.has('Durian')); // 输出: false -
清空集合
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); fruits.clear(); console.log(fruits); // 输出: Set {} -
遍历集合
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); fruits.forEach(fruit => {console.log(fruit); }); // 输出: // Apple // Banana // Cherry -
获取集合大小
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); console.log(fruits.size); // 输出: 3 -
转换为数组
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); let arr: string[] = Array.from(fruits); console.log(arr); // 输出: ['Apple', 'Banana', 'Cherry']
4. 映射(Map)
4.1 创建 Map 对象
let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
]);
4.2 Map 类的常用函数和属性
-
属性
-
size: 返回映射的大小。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); console.log(personAge.size); // 输出: 3
-
-
方法
-
set(key: K, value: V): 设置键值对。let personAge: Map<string, number> = new Map(); personAge.set('Alice', 30); personAge.set('Bob', 25); console.log(personAge); // 输出: Map { 'Alice' => 30, 'Bob' => 25 } -
get(key: K): 获取指定键的值。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25] ]); console.log(personAge.get('Alice')); // 输出: 30 console.log(personAge.get('Bob')); // 输出: 25 -
has(key: K): 检查映射中是否存在指定键。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25] ]); console.log(personAge.has('Alice')); // 输出: true console.log(personAge.has('Charlie')); // 输出: false -
delete(key: K): 删除指定键及其值。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25] ]); personAge.delete('Bob'); console.log(personAge); // 输出: Map { 'Alice' => 30 } -
clear(): 清空映射。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); personAge.clear(); console.log(personAge); // 输出: Map {} -
forEach(callback: (value: V, key: K, map: Map<K, V>) => void): 对映射的每个键值对执行指定的操作。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); personAge.forEach((age, name) => {console.log(`${name} is ${age} years old.`); }); // 输出: // Alice is 30 years old. // Bob is 25 years old. // Charlie is 28 years old. -
keys(): 返回映射中所有键的迭代器。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); let keys = personAge.keys(); console.log(keys); // 输出: MapIterator { 'Alice', 'Bob', 'Charlie' } -
values(): 返回映射中所有值的迭代器。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); let values = personAge.values(); console.log(values); // 输出: MapIterator { 30, 25, 28 } -
entries(): 返回映射中所有键值对的迭代器。let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); let entries = personAge.entries(); console.log(entries); // 输出: MapIterator { ['Alice', 30], ['Bob', 25], ['Charlie', 28] }
-
5. 不同集合类型间的转换
5.1 数组与 Set 之间的转换
-
数组转 Set
let arr: string[] = ['Apple', 'Banana', 'Cherry']; let fruits: Set<string> = new Set(arr); console.log(fruits); // 输出: Set { 'Apple', 'Banana', 'Cherry' } -
Set 转数组
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); let arr: string[] = Array.from(fruits); console.log(arr); // 输出: ['Apple', 'Banana', 'Cherry']
5.2 数组与 Map 之间的转换
-
数组转 Map
let arr: [string, number][] = [['Alice', 30], ['Bob', 25], ['Charlie', 28]]; let personAge: Map<string, number> = new Map(arr); console.log(personAge); // 输出: Map { 'Alice' => 30, 'Bob' => 25, 'Charlie' => 28 } -
Map 转数组
let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); let arr: [string, number][] = Array.from(personAge.entries()); console.log(arr); // 输出: [['Alice', 30], ['Bob', 25], ['Charlie', 28]]
5.3 Set 与 Map 之间的转换
-
Set 转 Map
let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']); let fruitMap: Map<string, number> = new Map(); fruits.forEach(fruit => {fruitMap.set(fruit, 1); }); console.log(fruitMap); // 输出: Map { 'Apple' => 1, 'Banana' => 1, 'Cherry' => 1 } -
Map 转 Set
let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28] ]); let keys: Set<string> = new Set(personAge.keys()); let values: Set<number> = new Set(personAge.values()); console.log(keys); // 输出: Set { 'Alice', 'Bob', 'Charlie' } console.log(values); // 输出: Set { 30, 25, 28 }
总结
通过以上内容,我们详细介绍了 TypeScript 中常用的集合类型及其操作方法。掌握这些集合类型及其转换方法,可以帮助开发者更高效地管理和操作数据。以下是一些关键点:
- 数组(Array) 是有序的数据集合,支持多种操作,如
push,pop,forEach,map,filter等。 - 元组(Tuple) 是固定长度和固定类型的数组,适用于存储固定结构的数据。
- 集合(Set) 是不包含重复元素的无序集合,适用于需要唯一性保证的场景。
- 映射(Map) 是键值对的集合,适用于需要快速查找和关联数据的场景。