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 lsti splice(i, 1)
按值删除 remove(value) 先indexOf(value)再splice(index, 1)
遍历元素 for item in list for...of 循环
遍历索引元素 enumerate(list) for循环或forEach((item, index) => {})
切片 lsta:b slice(a,b)
过滤 列表推导 filter()

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

相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
卡布鲁1 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
李少兄1 天前
JavaScript 隐式全局变量解析
javascript
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型