新聞中心
在TypeScript中,對象數(shù)組是一種包含多個對象的數(shù)組,每個對象可以具有不同的屬性和值,以下是關(guān)于TypeScript對象數(shù)組的詳細解釋:

創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站設(shè)計、成都網(wǎng)站設(shè)計、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的隰縣網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
1、創(chuàng)建對象數(shù)組
要創(chuàng)建一個對象數(shù)組,首先需要定義一個對象類型,然后使用該類型創(chuàng)建多個對象,并將它們放入一個數(shù)組中。
“`typescript
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: "張三", age: 30 },
{ name: "李四", age: 25 },
{ name: "王五", age: 28 },
];
“`
2、訪問對象數(shù)組中的對象
要訪問對象數(shù)組中的對象,可以使用數(shù)組索引。
“`typescript
const firstPerson = people[0]; // { name: "張三", age: 30 }
const secondPerson = people[1]; // { name: "李四", age: 25 }
“`
3、修改對象數(shù)組中的對象
要修改對象數(shù)組中的對象,可以直接通過數(shù)組索引對其進行賦值。
“`typescript
people[0].name = "趙六"; // { name: "趙六", age: 30 }
people[1].age = 26; // { name: "李四", age: 26 }
“`
4、添加新的對象到對象數(shù)組中
要向?qū)ο髷?shù)組中添加新的對象,可以使用push()方法。
“`typescript
const newPerson: Person = { name: "孫七", age: 22 };
people.push(newPerson); // [{ name: "趙六", age: 30 }, { name: "李四", age: 26 }, { name: "孫七", age: 22 }]
“`
5、從對象數(shù)組中刪除對象
要從對象數(shù)組中刪除對象,可以使用splice()方法。
“`typescript
people.splice(1, 1); // [{ name: "趙六", age: 30 }, { name: "孫七", age: 22 }]
“`
6、遍歷對象數(shù)組中的對象
要遍歷對象數(shù)組中的對象,可以使用for...of循環(huán)或forEach()方法。
“`typescript
// 使用 for…of 循環(huán)遍歷對象數(shù)組
for (const person of people) {
console.log(person.name, person.age); // 輸出每個對象的 name 和 age 屬性
}
// 使用 forEach() 方法遍歷對象數(shù)組
people.forEach((person) => {
console.log(person.name, person.age); // 輸出每個對象的 name 和 age 屬性
});
“`
分享名稱:TypeScript對象數(shù)組
鏈接分享:http://m.fisionsoft.com.cn/article/dpgosgp.html


咨詢
建站咨詢
