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 数组操作。

相关推荐
宿州派大星34 分钟前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
承渊政道2 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(开源大模型ChatGLM高级定制化应用实战)
人工智能·pytorch·python·llm·模型微调·glm
半个落月6 小时前
LangSmith 全链路观测(下):用 Dataset 与 LLM Judge 量化评估 RA
javascript·langchain
半个落月7 小时前
LangSmith 全链路观测(上):用 LangGraph 与 Milvus 构建可追踪的 RAG 客服
javascript·langchain
半个落月8 小时前
LangChain.js Agent 中间件实战:生命周期、动态工具与文件权限
javascript·langchain
Smoothcloud润云8 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook8 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴9 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
志尊宝9 小时前
Vue3 零基础每日笔记(082):文件上传实战——el-upload 校验、自定义上传、头像预览
前端·javascript·vue.js·笔记·#javascript·#vue.js
诺伦9 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索