TypeScript对象数组
更新时间:2026-11-30 10:55:16
在TypeScript中(zhong),对象对象数组是数组一种包含多个对象的数(shu)组,每个(ge)对象可以具有不同的对象属性和值,以(yi)下(xia)是数组关于TypeScript对象数组的详细解释:(图片来源网络,侵删)

要创建一个(ge)对(dui)象数组,数组首先需要定义一个对象类型,对象然后使用该类型创建多个(ge)对象,数组并(bing)将它(ta)们放入一个数组中(zhong)。对(dui)象(xiang)


interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: "张三",数(shu)组 age: 30 },
{ name: "李四(si)", age: 25 },
“`
2、访问对象数组中的对象对象
要访问对象数组中的对象,可以使用数组索引。数组
“`typescript
const firstPerson = people[0]; // { name: "张三",对象 age: 30 }
const secondPerson = people[1]; // { name: "李四", age: 25 }
“`
3、修改对象数组(zu)中的数组对象
要修改对象数组中的(de)对象,可以直(zhi)接通过(guo)数组索引对其进行赋值。对象
“`typescript
people[0].name = "赵六"; // { name: "赵六", age: 30 }
people[1].age = 26; // { name: "李四", age: 26 }
“`
4、添加新的对象到对象数组中
要向对象数组中添加(jia)新的对象,可以使用push()方法。
“`typescript
const newPerson: Person = { name: "孙七", age: 22 };
people.push(newPerson); // [{ name: "赵六", age: 30 }, { name: "李四", age: 26 }, { name: "孙七", age: 22 }]
“`
5、从对象数组中删除对象
要从对象数组中删除对象,可(ke)以使用splice()方法。
“`typescript
people.splice(1, 1); // [{ name: "赵六", age: 30 }, { name: "孙七", age: 22 }]
“`
6、遍历对象数(shu)组中的(de)对象
要(yao)遍历对象数组中的对象,可以使用for...of循环或forEach()方法。
“`typescript
// 使用 for…of 循环遍历对象数组(zu)
for (const person of people) {
console.log(person.name, person.age); // 输出每个对象的 name 和 age 属性
}
// 使用 forEach() 方法遍历对象数组
people.forEach((person) => {
console.log(person.name, person.age); // 输出每个对象的 name 和 age 属性
});
“`

