TypeScript 中使用物件遍歷 For-In 語句


在 TypeScript 中,物件包含屬性及其值。我們可以使用 for-in 迴圈語句遍歷物件的每個屬性並獲取其值。

本教程將教會我們透過不同的示例遍歷物件鍵值對。此外,我們還將學習在遍歷物件屬性時可能遇到哪些錯誤以及如何快速修復這些錯誤。

語法

使用者可以按照以下語法使用 for-in 迴圈語句遍歷可迭代物件的屬性。

For (var_name in object){
   Statements or block to execute;
}

現在,我們將檢視不同的示例來遍歷物件屬性。

步驟

  • 步驟 1 - 定義一個具有不同屬性的物件。

  • 步驟 2 - 使用 for…in 語句遍歷物件以訪問物件的鍵。

  • 步驟 3 - 列印物件的屬性。

示例 1

在下面的示例中,我們建立了 student 物件,其中包含 students_name、age 和 role 屬性。我們使用 for-in 迴圈語句訪問 student 物件的鍵。在訪問鍵之後,我們還訪問了特定鍵的值。

// defining the student object
const student = {
   student_name: "Shubham",
   role: "Content writer",
   age: 22,
};

// iterating through the student object
for (const key in student) {
   console.log("The " + key + " of the student is " + object[key]);
}

編譯後,它將生成以下 JavaScript 程式碼:

// defining the student object
var student = {
   student_name: "Shubham",
   role: "Content writer",
   age: 22
};

// iterating through the student object
for (var key in student) {
   console.log("The " + key + " of the student is " + student[key]);
}

輸出

以上程式碼將產生以下輸出:

The student_name of the student is Shubham
The role of the student is Content writer
The age of the student is 22

現在讓我們定義一個特定型別的物件,該物件還包含方法和陣列作為屬性值。

在下一個示例中,我們將遵循以下步驟:

  • 步驟 1 - 建立一個名為 Table 的介面。

  • 步驟 2 - 在 Table 介面中定義字串型別的 brand 和 color 屬性。此外,定義數字陣列型別的 sizes 屬性,以及返回表格價格的 get_price() 方法。

  • 步驟 3 - 建立 Table 型別的 table_obj,使用正確的值初始化其屬性,並定義 get_price() 方法。

  • 步驟 4 - 使用 for-in 迴圈遍歷 table_obj 的每個鍵。

  • 步驟 5 - 在 for-in 迴圈內,使用物件名稱和方括號表示法訪問特定鍵的值。此外,以格式化的方式列印鍵值對。

示例 2

以下示例演示了一個特定型別的物件,該物件還包含方法和陣列作為屬性值。在輸出中,我們可以看到 get_price 屬性的值是一個完整的函式,sizes 屬性的值是一個數字陣列。

// Creating the table interface
interface Table {
   brand: string;
   color: string;
   sizes: Array<number>;
   get_price(): number;
}
// creating the table_obj of type Table
let table_obj: Table = {
   brand: "woodBrand",
   color: " grey",
   sizes: [10, 40, 30, 20],
   get_price(): number {
      return 10;
   },
};
// Iterating through the table_obj
for (let key in table_obj) {
   console.log("The value of " + key + " in table_obj is " + table_obj[key]);
}

編譯後,它將生成以下 JavaScript 程式碼:

// creating the table_obj of type Table
var table_obj = {
   brand: "woodBrand",
   color: " grey",
   sizes: [10, 40, 30, 20],
   get_price: function () {
      return 10;
   }
};
// Iterating through the table_obj
for (var key in table_obj) {
   console.log("The value of " + key + " in table_obj is " + table_obj[key]);
}

輸出

以上程式碼將產生以下輸出:

The value of brand in table_obj is woodBrand
The value of color in table_obj is grey
The value of sizes in table_obj is 10,40,30,20
The value of get_price in table_obj is function () {
   return 10;
}

在本教程中,使用者學習瞭如何使用 for-in 迴圈遍歷物件屬性值。我們已經看到了兩個不同的例子。第一個例子非常容易建立,適合初學者。第二個例子還包含介面

更新於: 2023年1月16日

6K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告