当前位置:首页 > 行业动态 > 正文

TypeScript 字典

在 TypeScript 中,可以使用接口(Interface)来定义字典,字典是一种键值对的数据结构,其中每个键都对应一个值,下面是一个示例:

1、定义字典接口:

interface Dictionary {
  [key: string]: any; // 使用方括号语法表示键的类型为字符串,值的类型为任意类型
} 

2、创建字典实例:

TypeScript 字典

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、遍历字典的键和值:

TypeScript 字典

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、修改字典中的值:

TypeScript 字典

myDict.age = 31;
console.log(myDict.age); // 输出 31 

7、删除字典中的键值对:

delete myDict.city;
console.log(myDict.city); // 输出 undefined,因为已删除该键值对