TS数组的全部方法总结

发布于:2024-12-06 ⋅ 阅读:(210) ⋅ 点赞:(0)

在这里插入图片描述


在 TypeScript 中,数组方法是 JavaScript 数组方法的扩展。大多数方法是从 JavaScript 继承的,但由于 TypeScript 的类型系统,你可以获得更好的类型检查和推导。以下是 TypeScript 中数组的全部常见方法及其描述:

✨基本操作

📌 push(...items: T[]): number
向数组的末尾添加一个或多个元素,并返回新的数组长度。

const arr: number[] = [1, 2];
arr.push(3);  // arr = [1, 2, 3]

📌pop(): T | undefined
从数组中移除并返回最后一个元素。如果数组为空,返回 undefined。

const arr = [1, 2, 3];
const last = arr.pop();  // last = 3, arr = [1, 2]

📌shift(): T | undefined
从数组的开头移除并返回第一个元素。如果数组为空,返回 undefined。

const arr = [1, 2, 3];
const first = arr.shift();  // first = 1, arr = [2, 3]

📌unshift(...items: T[]): number
将一个或多个元素添加到数组的开头,并返回新的数组长度。

const arr = [1, 2];
arr.unshift(0);  // arr = [0, 1, 2]

📌splice(start: number, deleteCount?: number, …items: T[]): T[]
从指定位置删除元素,并可以插入新的元素。返回被删除的元素。

const arr = [1, 2, 3, 4];
const removed = arr.splice(1, 2, 5, 6);  // removed = [2, 3], arr = [1, 5, 6, 4]

✨查询和查找

📌concat(...arrays: ConcatArray<T>[]): T[]
合并多个数组或值,并返回一个新的数组。

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = arr1.concat(arr2);  // arr3 = [1, 2, 3, 4]

📌join(separator?: string): string
将数组的所有元素转换为字符串,并用指定的分隔符连接。

const arr = [1, 2, 3];
const str = arr.join(", ");  // str = "1, 2, 3"

📌indexOf(searchElement: T, fromIndex?: number): number
返回数组中某个元素的第一个索引。如果找不到,返回 -1。

const arr = [1, 2, 3];
const index = arr.indexOf(2);  // index = 1

📌lastIndexOf(searchElement: T, fromIndex?: number): number
返回数组中某个元素的最后一个索引。如果找不到,返回 -1。

const arr = [1, 2, 3, 2];
const index = arr.lastIndexOf(2);  // index = 3

📌includes(searchElement: T, fromIndex?: number): boolean
判断数组中是否包含某个元素,返回 true 或 false。

const arr = [1, 2, 3];
const isExist = arr.includes(2);  // true

📌find(callback: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T | undefined
返回数组中满足条件的第一个元素。如果找不到,返回 undefined。

const arr = [1, 2, 3];
const found = arr.find(item => item > 1);  // found = 2

📌findIndex(callback: (value: T, index: number, array: T[]) => unknown, thisArg?: any): number
返回数组中满足条件的第一个元素的索引。如果找不到,返回 -1。

const arr = [1, 2, 3];
const index = arr.findIndex(item => item > 1);  // index = 1

✨迭代

📌forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void
对数组的每个元素执行一次给定的函数。

const arr = [1, 2, 3];
arr.forEach((item, index) => console.log(item, index));

📌map<U>(callback: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]
创建一个新数组,数组中的元素是通过调用指定函数对原数组的每个元素进行操作后的结果。

const arr = [1, 2, 3];
const mapped = arr.map(x => x * 2);  // mapped = [2, 4, 6]

📌filter(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]
创建一个新数组,包含所有满足条件的元素。

const arr = [1, 2, 3, 4];
const filtered = arr.filter(x => x > 2);  // filtered = [3, 4]

📌reduce(callback: (accumulator: U, value: T, index: number, array: T[]) => U, initialValue?: U): U
对数组中的所有元素执行累加(或其他指定的操作)。

const arr = [1, 2, 3];
const sum = arr.reduce((acc, curr) => acc + curr, 0);  // sum = 6

📌reduceRight(callback: (accumulator: U, value: T, index: number, array: T[]) => U, initialValue?: U): U
与 reduce 类似,但是从右到左迭代。

const arr = [1, 2, 3];
const result = arr.reduceRight((acc, curr) => acc + curr, 0);  // result = 6

📌some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean
判断数组中是否有至少一个元素满足条件。

const arr = [1, 2, 3];
const hasEven = arr.some(x => x % 2 === 0);  // hasEven = true

📌every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean
判断数组中是否所有元素都满足条件。

const arr = [1, 2, 3];
const allGreaterThanZero = arr.every(x => x > 0);  // allGreaterThanZero = true

✨排序与反转

📌sort(compareFn?: (a: T, b: T) => number): T[]
对数组的元素进行排序。如果传入 compareFn,则根据该函数的结果进行排序。

const arr = [3, 1, 2];
arr.sort((a, b) => a - b);  // arr = [1, 2, 3]

📌reverse(): T[]
反转数组中的元素顺序。

const arr = [1, 2, 3];
arr.reverse();  // arr = [3, 2, 1]

✨数组转换

📌slice(start?: number, end?: number): T[]
返回一个新数组,包含原数组的指定部分。

const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3);  // sliced = [2, 3]

📌toString(): string
返回数组的字符串表示。

const arr = [1, 2, 3];
const str = arr.toString();  // str = "1,2,3"

📌toLocaleString(locales?: string | string[], options?: Object): string
返回数组的本地化字符串表示。

const arr = [1234567.89];
console.log(arr.toLocaleString('en-US'));  // 输出: "1,234,567.89"(美国英语的千位分隔符为逗号)
console.log(arr.toLocaleString('de-DE'));  // 输出: "1.234.567,89"(德国德语的千位分隔符为点,十进制为逗号)

📌copyWithin(target: number, start: number, end?: number): T[]
将数组的一部分复制到另一位置,并返回修改后的数组。此方法不会改变数组的长度。

const arr = [1, 2, 3, 4];
arr.copyWithin(2, 0, 2);  // arr = [1, 2, 1, 2]

📌fill(value: T, start?: number, end?: number): T[]
用指定的值填充数组的一部分,并返回修改后的数组。

const arr = [1, 2, 3];
arr.fill(0, 1, 3);  // arr = [1, 0, 0]

📌from(arrayLike: ArrayLike<T>, mapFn?: (value: any, index: number) => T, thisArg?: any): T[]
将类似数组的对象或可迭代对象转换为数组。

const str = 'hello';
const arr = Array.from(str);  // arr = ['h', 'e', 'l', 'l', 'o']

📌keys(): IterableIterator<number>
返回一个新的数组的索引的迭代器。

const arr = [1, 2, 3];
const keys = arr.keys();
for (let key of keys) {
  console.log(key);  // 输出 0, 1, 2
}

📌values(): IterableIterator<T>

返回一个新的数组的值的迭代器。
const arr = [1, 2, 3];
const values = arr.values();
for (let value of values) {
  console.log(value);  // 输出 1, 2, 3
}

📌entries(): IterableIterator<[number, T]>
返回一个新的数组的键值对的迭代器(每个项是一个 [index, value] 对)。

const arr = [1, 2, 3];
const entries = arr.entries();
for (let [index, value] of entries) {
  console.log(index, value);  // 输出 0 1, 1 2, 2 3
}

✨数组的空值与检测

📌isArray(value: any): value is T[]
检查给定的值是否是一个数组。

const arr = [1, 2, 3];
const result = Array.isArray(arr);  // result = true
const notArray = Array.isArray({});  // result = false

✨性能与优化

📌flat(depth: number = 1): T[]
将嵌套的数组展平,返回一个新数组。depth 参数表示展平的层级,默认为 1。

const arr = [1, [2, [3, 4]]];
const flatArr = arr.flat(2);  // flatArr = [1, 2, 3, 4]

📌flatMap<U>(callback: (value: T, index: number, array: T[]) => U | U[], thisArg?: any): U[]
对数组的每个元素执行回调函数,并将结果展平。

const arr = [1, 2, 3];
const flatMapped = arr.flatMap(x => [x, x * 2]);  // flatMapped = [1, 2, 2, 4, 3, 6]

✨类型相关的数组方法

📌findLast(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T | undefined (ES2022 新增)
查找数组中最后一个满足条件的元素。

const arr = [1, 2, 3, 4];
const lastEven = arr.findLast(x => x % 2 === 0);  // lastEven = 4

📌at(index: number): T | undefined (ES2022 新增)
获取指定索引的元素,支持负数索引。

const arr = [1, 2, 3];
const element = arr.at(-1);  // element = 3

✨数组的其他功能

🚩sort() 与 reverse() 的组合使用
可以通过结合 sort() 和 reverse() 来倒排数组:

const arr = [1, 2, 3, 4];
arr.sort((a, b) => b - a);  // arr = [4, 3, 2, 1]

🚩fill() 方法用于初始化数组
你可以通过 fill() 来填充数组,通常用于初始化数组。

const arr = new Array(5).fill(0);  // arr = [0, 0, 0, 0, 0]

🚩Array.from() 与 map() 结合使用
Array.from() 方法将类数组对象转换为数组,并可通过 map() 做进一步转换。

const arr = Array.from('123', (x) => parseInt(x));  // arr = [1, 2, 3]

✨性能注意

数组操作在处理大量数据时可能会遇到性能瓶颈,尤其是涉及到以下操作:
1️⃣ push() 和 shift():push 是 O(1) 操作,但 shift 是 O(n),因为它会重新排列数组中的元素。
2️⃣ unshift():这是 O(n) 操作,因为它会将所有元素向后移动以腾出空间。
3️⃣ concat():对于非常大的数组,concat 可能会导致性能问题,因为它会创建一个新数组,并复制所有元素。

✨数组的多维数组

对于多维数组,你可以通过 map()、reduce()、flat() 等方法进行处理。
例如,遍历二维数组:

const arr = [
  [1, 2],
  [3, 4]
];
arr.map(subArray => subArray.reduce((sum, item) => sum + item, 0));  // [3, 7]

网站公告

今日签到

点亮在社区的每一天
去签到