TypeScript 中类似 Python list 的数组操作及示例

TypeScript 中类似 Python list 的数组操作及示例

在 Python 中,list(列表)是常用的数据结构,支持追加、排序、插入等操作。TypeScript 中的数组(Array)与 Python list 功能类似,也提供了丰富的方法实现这些操作。下面一一对应讲解并给出示例。

一、数组的定义(类似 Python list 初始化)

Python list 定义

ini 复制代码
# 空列表
py_list = []
# 带初始值的列表
py_list = [1, 2, 3, 4]

TypeScript 数组定义

ini 复制代码
// 空数组(指定类型,推荐)
let tsArray: number[] = [];
// 带初始值的数组
let tsArray: number[] = [1, 2, 3, 4];
// 也可用泛型表示
let tsArray: Array<number> = [1, 2, 3, 4];
// 多维数组
let matrix: number[][] = [[1, 2], [3, 4]];

二、追加元素(类似 Python list.append ())

Python list 追加

scss 复制代码
py_list = [1, 2, 3]
py_list.append(4)
print(py_list)  # 输出:[1, 2, 3, 4]

py_list.extend([5, 6])  # 扩展list
print(py_list)  # 输出:[1, 2, 3, 4, 5, 6]

TypeScript 数组追加

使用push()方法,在数组末尾添加元素,与append()功能一致。

typescript 复制代码
let tsArray: number[] = [1, 2, 3];
tsArray.push(4);
console.log(tsArray);  // 输出:[1, 2, 3, 4]

tsArray.push(...[5, 6]);   # 数组合并
console.log(tsArray);  // 输出:[1, 2, 3, 4, 5, 6]

let fruits: string[] = ["apple", "banana"];
fruits.push("orange"); // ["apple", "banana", "orange"]
fruits.push(...["grape", "mango"]); // 追加多个元素
fruits.unshift("kiwi"); // 开头追加

三、排序(类似 Python list.sort ())

Python list 排序

ini 复制代码
py_list = [3, 1, 4, 2]
py_list.sort()  # 升序排序
print(py_list)  # 输出:[1, 2, 3, 4]
py_list.sort(reverse=True)  # 降序排序
print(py_list)  # 输出:[4, 3, 2, 1]

TypeScript 数组排序

使用sort()方法,默认按字符串 Unicode 码点排序,对于数字排序需传入比较函数。

typescript 复制代码
let tsArray: number[] = [3, 1, 4, 2];
// 升序排序
tsArray.sort((a, b) => a - b);
console.log(tsArray);  // 输出:[1, 2, 3, 4]
// 降序排序
tsArray.sort((a, b) => b - a);
console.log(tsArray);  // 输出:[4, 3, 2, 1]

nums.reverse();  // 反序


//自定义排序,快速排序
function quickSort(arr: number[]): number[] {
  if (arr.length <= 1) return arr;
  const pivot = arr[arr.length - 1];
  const left = arr.filter((x, i) => x < pivot && i !== arr.length - 1);
  const right = arr.filter(x => x > pivot);
  return [...quickSort(left), pivot, ...quickSort(right)];
}

四、插入元素(类似 Python list.insert ())

Python list 插入

scss 复制代码
py_list = [1, 2, 4]
py_list.insert(2, 3)  # 在索引2处插入3
print(py_list)  # 输出:[1, 2, 3, 4]

TypeScript 数组插入

使用splice()方法,第一个参数是插入位置,第二个参数为 0(表示不删除元素),第三个及以后参数是要插入的元素。

typescript 复制代码
let tsArray: number[] = [1, 2, 4];
tsArray.splice(2, 0, 3);  // 在索引2处插入3
console.log(tsArray);  // 输出:[1, 2, 3, 4]

let colors: string[] = ["red", "blue"];
colors.splice(1, 0, "green"); // 索引1处插入,不删除元素 → ["red", "green", "blue"]

五、删除元素(类似 Python list 的 pop ()、remove ())

Python list 删除

scss 复制代码
py_list = [1, 2, 3, 4]
# 根据索引删除(pop)
py_list.pop(1)  # 删除索引1的元素
print(py_list)  # 输出:[1, 3, 4]
# 根据值删除(remove)
py_list.remove(3)
print(py_list)  # 输出:[1, 4]

TypeScript 数组删除

  • 根据索引删除:用splice(索引, 1),第二个参数 1 表示删除 1 个元素。
  • 根据值删除:先通过indexOf()找到值的索引,再用splice()删除。
ini 复制代码
let tsArray: number[] = [1, 2, 3, 4];
// 根据索引删除(类似pop)
tsArray.splice(1, 1);  // 删除索引1的元素
console.log(tsArray);  // 输出:[1, 3, 4]
// 根据值删除(类似remove)
const valueToRemove = 3;
const index = tsArray.indexOf(valueToRemove);
if (index !== -1) {  // 确保找到了该值
  tsArray.splice(index, 1);
}
console.log(tsArray);  // 输出:[1, 4]


colors.pop(); // 删除并返回最后一个
colors.shift(); // 删除并返回第一个
colors.splice(0, 1); // 从索引0删除1个元素
const filtered = colors.filter(color => color !== "green"); // 条件删除,返回新数组

六、遍历元素(类似 Python 的 for 循环遍历)

Python list 遍历

python 复制代码
py_list = [1, 2, 3, 4]
# 遍历元素
for item in py_list:
    print(item)
# 遍历索引和元素
for index, item in enumerate(py_list):
    print(f"索引{index}:{item}")

TypeScript 数组遍历

  • 遍历元素:用for...of循环。
  • 遍历索引和元素:用for循环或forEach()方法。
typescript 复制代码
let tsArray: number[] = [1, 2, 3, 4];
// 遍历元素(类似for item in py_list)
for (const item of tsArray) {
  console.log(item);
}
// 遍历索引和元素(类似enumerate)
// 方法1:for循环,需要索引时
for (let index = 0; index < tsArray.length; index++) {
  console.log(`索引${index}:${tsArray[index]}`);
}
// 方法2:forEach()
tsArray.forEach((item, index) => {
  console.log(`索引${index}:${item}`);
});
list.forEach(x => console.log(x));

// map() 生成新数组(如转换数据)
const doubled = arr.map(x => x * 2);

// reduce() 累积计算(如求和)
const sum = arr.reduce((acc, val) => acc + val, 0);

七、操作对比总结

操作 Python list 方法 TypeScript 数组方法
定义 [] 或 list() number[] 或 Array
追加单个元素 append(value) push(value)
追加多个元素 extend(iter) push(...iter)
排序(升序) sort() sort((a, b) => a - b)
排序(降序) sort(reverse=True) sort((a, b) => b - a)
反转 reverse() reverse()
插入元素 insert(index, value) splice(index, 0, value)
按索引删除 pop(index) splice(index, 1)
删除末尾 pop() pop()
按下标删除 del lst[i] splice(i, 1)
按值删除 remove(value) 先indexOf(value)再splice(index, 1)
遍历元素 for item in list for...of 循环
遍历索引元素 enumerate(list) for循环或forEach((item, index) => {})
切片 lst[a:b] slice(a,b)
过滤 列表推导 filter()

通过以上对比可以看出,TypeScript 数组的操作与 Python list 类似,只是方法名和语法略有差异。掌握这些对应关系,能帮助 Python 开发者快速上手 TypeScript 数组操作。

相关推荐
子兮曰6 小时前
OpenClaw架构揭秘:178k stars的个人AI助手如何用Gateway模式统一控制12+通讯频道
前端·javascript·github
冷雨夜中漫步6 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴6 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再7 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
百锦再7 小时前
React编程高级主题:测试代码
android·前端·javascript·react.js·前端框架·reactjs
颜酱8 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
喵手8 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934738 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy8 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
小迷糊的学习记录9 小时前
Vuex 与 pinia
前端·javascript·vue.js