Typescript學習教程,從入門到精通,TypeScript 集合類型語法知識點及案例代碼(11)

TypeScript 集合類型語法知識點及案例代碼

TypeScript 提供了多種集合類型,用于存儲和管理數據。以下將詳細介紹 數組(Array)元組(Tuple)集合(Set)映射(Map),包括其語法、常用操作及案例代碼。


1. 數組(Array)

1.1 創建數組對象

在 TypeScript 中,數組可以通過以下幾種方式創建:

  • 使用方括號語法

    let fruits: string[] = ['Apple', 'Banana', 'Cherry'];
    let numbers: number[] = [1, 2, 3, 4, 5];
    
  • 使用泛型語法

    let fruits: Array<string> = ['Apple', 'Banana', 'Cherry'];
    let numbers: Array<number> = [1, 2, 3, 4, 5];
    
  • 使用 Array 構造函數

    let fruits: string[] = new Array('Apple', 'Banana', 'Cherry');
    let numbers: number[] = new Array(1, 2, 3, 4, 5);
    

1.2 Array 類常用函數和屬性

  • 屬性

    • length: 返回數組的長度。

      let arr: number[] = [1, 2, 3];
      console.log(arr.length); // 輸出: 3
      
  • 方法

    • push(item: T): 向數組末尾添加一個元素。

      let arr: number[] = [1, 2, 3];
      arr.push(4);
      console.log(arr); // 輸出: [1, 2, 3, 4]
      
    • pop(): 移除并返回數組的最后一個元素。

      let arr: number[] = [1, 2, 3];
      let last = arr.pop();
      console.log(last); // 輸出: 3
      console.log(arr);  // 輸出: [1, 2]
      
    • shift(): 移除并返回數組的第一個元素。

      let arr: number[] = [1, 2, 3];
      let first = arr.shift();
      console.log(first); // 輸出: 1
      console.log(arr);   // 輸出: [2, 3]
      
    • unshift(item: T): 向數組開頭添加一個元素。

      let arr: number[] = [1, 2, 3];
      arr.unshift(0);
      console.log(arr); // 輸出: [0, 1, 2, 3]
      
    • splice(start: number, deleteCount?: number, ...items: T[]): 更改數組內容。

      let arr: number[] = [1, 2, 3, 4, 5];
      arr.splice(2, 1, 6); // 從索引2開始,刪除1個元素,插入6
      console.log(arr); // 輸出: [1, 2, 6, 4, 5]
      
    • slice(begin?: number, end?: number): 返回數組的一個片段。

      let arr: number[] = [1, 2, 3, 4, 5];
      let sliced = arr.slice(1, 3);
      console.log(sliced); // 輸出: [2, 3]
      
    • forEach(callback: (value: T, index: number, array: T[]) => void): 對數組的每個元素執行指定的操作。

      let arr: number[] = [1, 2, 3];
      arr.forEach((value, index) => {console.log(`Index ${index}: ${value}`);
      });
      // 輸出:
      // Index 0: 1
      // Index 1: 2
      // Index 2: 3
      
    • map<U>(callback: (value: T, index: number, array: T[]) => U): 對數組的每個元素執行指定的操作,并返回一個新數組。

      let arr: number[] = [1, 2, 3];
      let doubled = arr.map(value => value * 2);
      console.log(doubled); // 輸出: [2, 4, 6]
      
    • filter(callback: (value: T, index: number, array: T[]) => boolean): 過濾數組,返回符合條件的元素組成的新數組。

      let arr: number[] = [1, 2, 3, 4, 5];
      let even = arr.filter(value => value % 2 === 0);
      console.log(even); // 輸出: [2, 4]
      

2. 元組(Tuple)

2.1 定義元組和賦值

元組是固定長度和固定類型的數組。

// 定義一個包含字符串和數字的元組
let person: [string, number] = ['Alice', 30];// 賦值
person = ['Bob', 25];

2.2 元組常用操作

  • 訪問元素

    let person: [string, number] = ['Alice', 30];
    console.log(person[0]); // 輸出: 'Alice'
    console.log(person[1]); // 輸出: 30
    
  • 解構賦值

    let person: [string, number] = ['Alice', 30];
    let [name, age] = person;
    console.log(name); // 輸出: 'Alice'
    console.log(age);  // 輸出: 30
    
  • 添加元素

    let person: [string, number] = ['Alice', 30];
    person.push(28);
    console.log(person); // 輸出: ['Alice', 30, 28]
    
  • 遍歷元組

    let person: [string, number] = ['Alice', 30];
    person.forEach((value, index) => {console.log(`Index ${index}: ${value}`);
    });
    // 輸出:
    // Index 0: Alice
    // Index 1: 30
    
  • 長度屬性

    let person: [string, number] = ['Alice', 30];
    console.log(person.length); // 輸出: 2
    

3. 集合(Set)

3.1 創建 Set 對象

let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);

3.2 Set 類常用操作

  • 添加元素

    let fruits: Set<string> = new Set(['Apple', 'Banana']);
    fruits.add('Cherry');
    console.log(fruits); // 輸出: Set { 'Apple', 'Banana', 'Cherry' }
    
  • 刪除元素

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    fruits.delete('Banana');
    console.log(fruits); // 輸出: Set { 'Apple', 'Cherry' }
    
  • 檢查元素是否存在

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    console.log(fruits.has('Apple')); // 輸出: true
    console.log(fruits.has('Durian')); // 輸出: false
    
  • 清空集合

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    fruits.clear();
    console.log(fruits); // 輸出: Set {}
    
  • 遍歷集合

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    fruits.forEach(fruit => {console.log(fruit);
    });
    // 輸出:
    // Apple
    // Banana
    // Cherry
    
  • 獲取集合大小

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    console.log(fruits.size); // 輸出: 3
    
  • 轉換為數組

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    let arr: string[] = Array.from(fruits);
    console.log(arr); // 輸出: ['Apple', 'Banana', 'Cherry']
    

4. 映射(Map)

4.1 創建 Map 對象

let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
]);

4.2 Map 類的常用函數和屬性

  • 屬性

    • size: 返回映射的大小。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
      ]);
      console.log(personAge.size); // 輸出: 3
      
  • 方法

    • set(key: K, value: V): 設置鍵值對。

      let personAge: Map<string, number> = new Map();
      personAge.set('Alice', 30);
      personAge.set('Bob', 25);
      console.log(personAge); // 輸出: Map { 'Alice' => 30, 'Bob' => 25 }
      
    • get(key: K): 獲取指定鍵的值。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25]
      ]);
      console.log(personAge.get('Alice')); // 輸出: 30
      console.log(personAge.get('Bob'));   // 輸出: 25
      
    • has(key: K): 檢查映射中是否存在指定鍵。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25]
      ]);
      console.log(personAge.has('Alice')); // 輸出: true
      console.log(personAge.has('Charlie')); // 輸出: false
      
    • delete(key: K): 刪除指定鍵及其值。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25]
      ]);
      personAge.delete('Bob');
      console.log(personAge); // 輸出: Map { 'Alice' => 30 }
      
    • clear(): 清空映射。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
      ]);
      personAge.clear();
      console.log(personAge); // 輸出: Map {}
      
    • forEach(callback: (value: V, key: K, map: Map<K, V>) => void): 對映射的每個鍵值對執行指定的操作。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
      ]);
      personAge.forEach((age, name) => {console.log(`${name} is ${age} years old.`);
      });
      // 輸出:
      // Alice is 30 years old.
      // Bob is 25 years old.
      // Charlie is 28 years old.
      
    • keys(): 返回映射中所有鍵的迭代器。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
      ]);
      let keys = personAge.keys();
      console.log(keys); // 輸出: MapIterator { 'Alice', 'Bob', 'Charlie' }
      
    • values(): 返回映射中所有值的迭代器。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
      ]);
      let values = personAge.values();
      console.log(values); // 輸出: MapIterator { 30, 25, 28 }
      
    • entries(): 返回映射中所有鍵值對的迭代器。

      let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
      ]);
      let entries = personAge.entries();
      console.log(entries); // 輸出: MapIterator { ['Alice', 30], ['Bob', 25], ['Charlie', 28] }
      

5. 不同集合類型間的轉換

5.1 數組與 Set 之間的轉換

  • 數組轉 Set

    let arr: string[] = ['Apple', 'Banana', 'Cherry'];
    let fruits: Set<string> = new Set(arr);
    console.log(fruits); // 輸出: Set { 'Apple', 'Banana', 'Cherry' }
    
  • Set 轉數組

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    let arr: string[] = Array.from(fruits);
    console.log(arr); // 輸出: ['Apple', 'Banana', 'Cherry']
    

5.2 數組與 Map 之間的轉換

  • 數組轉 Map

    let arr: [string, number][] = [['Alice', 30], ['Bob', 25], ['Charlie', 28]];
    let personAge: Map<string, number> = new Map(arr);
    console.log(personAge); // 輸出: Map { 'Alice' => 30, 'Bob' => 25, 'Charlie' => 28 }
    
  • Map 轉數組

    let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
    ]);
    let arr: [string, number][] = Array.from(personAge.entries());
    console.log(arr); // 輸出: [['Alice', 30], ['Bob', 25], ['Charlie', 28]]
    

5.3 Set 與 Map 之間的轉換

  • Set 轉 Map

    let fruits: Set<string> = new Set(['Apple', 'Banana', 'Cherry']);
    let fruitMap: Map<string, number> = new Map();
    fruits.forEach(fruit => {fruitMap.set(fruit, 1);
    });
    console.log(fruitMap); // 輸出: Map { 'Apple' => 1, 'Banana' => 1, 'Cherry' => 1 }
    
  • Map 轉 Set

    let personAge: Map<string, number> = new Map([['Alice', 30],['Bob', 25],['Charlie', 28]
    ]);
    let keys: Set<string> = new Set(personAge.keys());
    let values: Set<number> = new Set(personAge.values());
    console.log(keys);   // 輸出: Set { 'Alice', 'Bob', 'Charlie' }
    console.log(values); // 輸出: Set { 30, 25, 28 }
    

總結

通過以上內容,我們詳細介紹了 TypeScript 中常用的集合類型及其操作方法。掌握這些集合類型及其轉換方法,可以幫助開發者更高效地管理和操作數據。以下是一些關鍵點:

  • 數組(Array) 是有序的數據集合,支持多種操作,如 push, pop, forEach, map, filter 等。
  • 元組(Tuple) 是固定長度和固定類型的數組,適用于存儲固定結構的數據。
  • 集合(Set) 是不包含重復元素的無序集合,適用于需要唯一性保證的場景。
  • 映射(Map) 是鍵值對的集合,適用于需要快速查找和關聯數據的場景。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/906971.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/906971.shtml
英文地址,請注明出處:http://en.pswp.cn/news/906971.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

在 Win 10 上,Tcl/Tk 腳本2個示例

參閱&#xff1a;Tcl/Tk 教程 set PATH 新增 D:\Git\mingw64\bin where tclsh D:\Git\mingw64\bin\tclsh.exe where wish D:\Git\mingw64\bin\wish.exe 編寫 test_tk.tcl 如下 #!/usr/bin/tclsh # test 文件對話框 package require Tk# 彈出文件選擇對話框&#xff0c;限…

Qt環境的搭建

Qt安裝 Qt開發環境需要安裝三個部分 1.C編譯器(不是vs) 2.Qt SDK 3.需要一個Qt的集成開發環境 說是需要三個部分,但實際上是需要安裝Qt SDK就足夠了 QtSDK可以直接去官網下載 下載完成后需要配置一下環境變量 可以直接在系統中搜索"編輯系統環境變量" 為什么要…

Vue3中reactive響應式使用注意事項

Vue 3 的 reactive 是創建響應式對象的核心 API&#xff0c;但在使用過程中有一些需要注意的事項&#xff1a; 1&#xff1a;基本使用限制 僅對對象類型有效&#xff1a;reactive 只能用于對象類型&#xff08;Object、Array、Map、Set 等&#xff09;&#xff0c;不能用于原始…

STM32+rt-thread使用MQTT協議連接騰訊物聯網平臺

STM32rt-thread使用MQTT協議連接騰訊物聯網平臺 一、騰訊云sdk下載1、進入騰訊物聯網平臺文件[點擊鏈接跳轉](https://cloud.tencent.com.cn/document/product/1081/48356)2、下載csdk 二、移植騰訊云sdk1、將上面解壓的文件夾復制到自己工程目錄下2、文件添加到自己工程 三、連…

【MySQL成神之路】MySQL函數總結

以下是MySQL函數的全面總結&#xff0c;包含概念說明和代碼示例&#xff1a; 一、MySQL函數分類 1. 字符串函數 -- CONCAT&#xff1a;連接字符串 SELECT CONCAT(Hello, , World); -- 輸出 Hello World -- SUBSTRING&#xff1a;截取子串 SELECT SUBSTRING(MySQL, 2, 3…

JavaScript 異步編程、對象/數組操作

異步編程 JavaScript 是單線程語言&#xff0c;通過事件循環機制處理異步操作。任務分為兩種&#xff1a; 宏任務(Macrotask): script整體代碼、setTimeout&#xff08;時間結束執行&#xff09;、setInterval&#xff08;間隔執行&#xff09;、I/O、UI渲染 微任務(Microtas…

中小制造企業網絡安全防護指南

考慮到文章內容較長&#xff0c;簡要內容圖片在文檔末尾&#xff0c;請直接翻閱到底部查看 引言&#xff1a;中小制造企業面臨的獨特網絡安全挑戰 中小制造企業 (SME) 在當今數字化浪潮中扮演著至關重要的角色&#xff0c;然而&#xff0c;伴隨技術進步而來的是日益嚴峻且獨特…

es學習小結

1.?客戶端類型? ?推薦場景? ?版本兼容性? Elasticsearch Java API Client 新項目、ES 8.x集群 8.x及以上 Spring Data Elasticsearch Spring生態項目、簡化ORM操作 ES 7.x-8.x&#xff08;需版本匹配&#xff09; Low-Level REST Client 需要底層HTTP控制、兼容多版本ES …

Axure項目實戰:智慧運輸平臺后臺管理端-訂單管理2(多級交互)

親愛的小伙伴,在您瀏覽之前,煩請關注一下,在此深表感謝!如有幫助請訂閱專欄! Axure產品經理精品視頻課已登錄CSDN可點擊學習https://edu.csdn.net/course/detail/40420 課程主題:訂單管理2 主要內容:中繼器篩選、表單跟隨菜單拖動、審批數據互通等 應用場景:訂單管理…

2025年——ComfyUI_連接HuggingFace及更改緩存路徑

本篇分享在 ComfyUI 中連接 huggingface 以及更改模型緩存路徑。 我們在使用 ComfyUI 的一些插件時&#xff0c;有些必要模型只能通過連接 huggingface 來緩存才能讓流程得以進行。但目前在上網不科學的情況下是無法打開 huggingface 網站的&#xff0c;好在國內有其鏡像網站&a…

wx.getPrivacySetting接口needAuthorization一直返回false

我們在開發小程序的隱私協議授權時往往會使用到wx.getPrivacySetting接口&#xff0c;當返回的needAuthorization為true時候提示我們需要去授權&#xff0c;但你們有沒有遇到過needAuthorization一直為false的情況呢&#xff0c;下面是最常見的三個解決方法&#xff0c;都完善了…

旅游信息檢索

旅游信息檢索 旅游信息檢索是系統中實現數據獲取和處理的關鍵環節&#xff0c;負責根據用戶輸入的目的地城市和出游天數&#xff0c;動態獲取并生成高質量的旅游數據。 模塊的工作流程分為以下幾個階段&#xff1a;首先&#xff0c;對用戶輸入的信息進行標準化處理&#xff0…

機器學習筆記【Week2】

一、多變量線性回歸&#xff08;Multivariate Linear Regression&#xff09; 為什么需要多變量&#xff1f; 現實問題中&#xff0c;一個目標可能受多個因素影響&#xff0c;比如預測房價時&#xff1a; x 1 x_1 x1?&#xff1a;面積 x 2 x_2 x2?&#xff1a;臥室數量 x 3…

Axure 基本用法學習筆記

一、元件操作基礎 1. 可見性控制 隱藏/顯示&#xff1a;可以設置元件的可見性&#xff0c;使元件在特定條件下隱藏或可見 應用場景&#xff1a;創建動態交互效果&#xff0c;如點擊按鈕顯示隱藏內容 2. 層級管理 層級概念&#xff1a;元件有上下層關系&#xff0c;上層元件…

aws平臺s3存儲桶夸域問題處理

當我們收到開發反饋s3存在跨域問題 解決步驟&#xff1a; 配置 S3 存儲桶的 CORS 設置&#xff1a; 登錄到 AWS 管理控制臺。轉到 S3 服務。選擇你存儲文件的 存儲桶。點擊 權限 標簽頁。在 跨域資源共享&#xff08;CORS&#xff09;配置 部分&#xff0c;點擊 編輯。 登陸…

【后端高階面經:微服務篇】7、1秒響應保障:超時控制如何成為高并發系統的“救火隊長”?

一、全鏈路超時建模:從用戶需求到系統分解 1.1 端到端時間預算分配 黃金公式: 用戶期望響應時間 = 網絡傳輸時間 + 服務處理時間 + 下游調用時間 + 緩沖時間典型分配策略(以1秒目標為例): 環節時間預算優化目標客戶端渲染100ms骨架屏(Skeleton)預渲染邊緣節點(CDN)…

前端遇到高并發如何解決重復請求

在前端開發中遇到高并發場景時&#xff0c;若不加控制容易出現重復請求&#xff0c;這可能導致接口壓力增加、數據異常、用戶體驗變差等問題。以下是前端防止/解決重復請求的常見方法&#xff0c;按不同場景歸類總結&#xff1a; &#x1f31f; 一、常見重復請求場景 用戶頻繁點…

老牌協議再升級,Ethernet IP轉Modbus TCP網關橋接精準灌裝系統

對于消費品包裝制造商而言&#xff0c;灌裝機是最關鍵且昂貴的設備之一。然而&#xff0c;許多公司卻難以應對生產過程中的灌裝波動&#xff0c;從而造成嚴重的財務和生產后果。 在本次網絡研討會中&#xff0c;我們將探討穩聯技術的ethernet ip轉modbus tcp&#xff08;WL-ABC…

骰子游戲(2023睿抗省賽)

骰子游戲 題目描述: 在某個游戲中有一個骰子游戲。 在游戲中&#xff0c;你需要投擲 5 個標準六面骰子&#xff08;骰子為一個正方體&#xff0c;6個面上分別有 1、2、3、4、5、6中的一個數字&#xff0c;骰子的質量均勻&#xff09;&#xff0c;投出的點數根據組合會獲得一…

CMake跨平臺編譯生成:從理論到實戰

一、引言 在當今軟件開發中&#xff0c;跨平臺開發已成為常態。無論是需要在Windows、Linux、macOS等多操作系統上運行&#xff0c;還是在不同的硬件架構&#xff08;如x86、ARM等&#xff09;間部署&#xff0c;跨平臺編譯生成都是一個無法回避的關鍵問題。CMake&#xff0c;…