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

1、定義字典接口:
interface Dictionary {
[key: string]: any; // 使用方括號語法表示鍵的類型為字符串,值的類型為任意類型
}
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、檢查字典中是否存在某個鍵:
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、刪除字典中的鍵值對:
delete myDict.city; console.log(myDict.city); // 輸出 undefined,因?yàn)橐褎h除該鍵值對
本文名稱:TypeScript字典
文章分享:http://m.fisionsoft.com.cn/article/dpcdsdi.html


咨詢
建站咨詢
