新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
TypeScript字典
在 TypeScript 中,可以使用接口(Interface)來定義字典,字典是一種鍵值對(duì)的數(shù)據(jù)結(jié)構(gòu),其中每個(gè)鍵都對(duì)應(yīng)一個(gè)值,下面是一個(gè)示例:

1、定義字典接口:
interface Dictionary {
[key: string]: any; // 使用方括號(hào)語法表示鍵的類型為字符串,值的類型為任意類型
}
2、創(chuàng)建字典實(shí)例:
const myDict: Dictionary = {
name: "John",
age: 30,
city: "New York"
};
3、訪問字典中的值:
console.log(myDict.name); // 輸出 "John" console.log(myDict.age); // 輸出 30 console.log(myDict.city); // 輸出 "New York"
4、遍歷字典的鍵和值:
for (const key in myDict) {
if (myDict.hasOwnProperty(key)) {
console.log(Key: ${key}, Value: ${myDict[key]});
}
}
5、檢查字典中是否存在某個(gè)鍵:
if (myDict.hasOwnProperty("name")) {
console.log("Name exists in the dictionary");
} else {
console.log("Name does not exist in the dictionary");
}
6、修改字典中的值:
myDict.age = 31; console.log(myDict.age); // 輸出 31
7、刪除字典中的鍵值對(duì):
delete myDict.city; console.log(myDict.city); // 輸出 undefined,因?yàn)橐褎h除該鍵值對(duì)
文章標(biāo)題:TypeScript字典
本文網(wǎng)址:http://www.5511xx.com/article/dpcdsdi.html


咨詢
建站咨詢
