如何在 TypeScript 中使用关联数组?
包含一个或多个元素的对象称为数组。每个元素可以是对象或简单数据类型。例如,您可以将日期、字符串和数字放在同一个数组中。信息也可以使用关联数组来存储。使用字符串作为索引的数组称为关联数组。
您可以创建一个在单个数组中使用数字和字符串索引的混合数组。只有当数组同时具有数字和字符串索引时,其长度才会反映具有数字索引的条目数量。在功能方面,关联数组和数字数组相似。但是,它们在索引的格式上有所不同。关联数组中的每个 ID 键都有对应的值。
在 TypeScript 中,关联数组是一个列出键及其对应值的接口。它可以像常规数组一样使用,但唯一的区别是它可以使用字符串而不是数字来访问。
语法
interface AssociativeArray {
[key: string]: string
}
var associative_array: AssociativeArray[] = []
associative_array['key'] = 'value'
console.log(associative_array['key'])
// Output:
// value
在上述语法中,我们声明了一个关联数组接口及其对象。它看起来与普通数组相同,但我们使用字符串"key"作为索引,并使用值"value"。我们使用键访问存储的值。
示例 1
在下面的示例中,我们使用关联数组存储一系列值,并使用字符串或键作为索引。我们将姓名、语言、姓名和电话号码存储在关联数组中,然后从中检索这些值。我们在控制台中显示了所有值。我们声明了一个接口 AssociativeArray 来存储关联数组的数据类型。
interface AssociativeArray {
[key: string]: string
}
var associative_array: AssociativeArray[] = []
associative_array['name'] = 'Tutorialspoint'
associative_array['language'] = 'TypeScript'
associative_array['roll'] = 12345
associative_array['phone'] = 9999999999
console.log('Name: ', associative_array['name'])
console.log('Language: ', associative_array['language'])
console.log('Roll: ', associative_array['roll'])
console.log('Phone: ', associative_array['phone'])
编译后,它将生成以下 JavaScript 代码 -
var associative_array = [];
associative_array['name'] = 'Tutorialspoint';
associative_array['language'] = 'TypeScript';
associative_array['roll'] = 12345;
associative_array['phone'] = 9999999999;
console.log('Name: ', associative_array['name']);
console.log('Language: ', associative_array['language']);
console.log('Roll: ', associative_array['roll']);
console.log('Phone: ', associative_array['phone']);
输出
上述代码将产生以下输出 -
Name: Tutorialspoint Language: TypeScript Roll: 12345 Phone: 9999999999
在输出中,我们显示了关联数组的所有存储值。
示例 2
在下面的示例中,我们将看到如何循环遍历关联数组。我们选取一个关联数组,该数组存储了不同语言版本的单词"hello"。循环遍历关联数组与循环普通数组不同,因为在本例中,我们将使用"for in"循环机制获取关联数组的键。我们还需要使用该键来获取关联数组的实际存储值。这是一种获取所有关联数组值的简单方法,无需手动逐个获取。我们声明了一个接口 AssociativeArray 来存储关联数组的数据类型。
interface AssociativeArray {
[key: string]: string
}
// 声明关联数组
var hello_associated_array: AssociativeArray[] = []
hello_associated_array['english'] = 'Hello'
hello_associated_array['spanish'] = 'hola'
hello_associated_array['french'] = 'Bonjour'
hello_associated_array['german'] = 'Guten tag'
hello_associated_array['italian'] = 'salve'
// 循环遍历关联数组
for (let key in hello_associated_array) {
console.log(key + ': ' + hello_associated_array[key])
}
编译后,它将生成以下 JavaScript 代码 -
// 声明关联数组
var hello_associated_array = [];
hello_associated_array['english'] = 'Hello';
hello_associated_array['spanish'] = 'hola';
hello_associated_array['french'] = 'Bonjour';
hello_associated_array['german'] = 'Guten tag';
hello_associated_array['italian'] = 'salve';
// 循环遍历关联数组
for (var key in hello_associated_array) {
console.log(key + ': ' + hello_associated_array[key]);
}
输出
上述代码将产生以下输出 -
english: Hello spanish: hola french: Bonjour german: Guten tag italian: salve
就像我们使用了 for in 循环机制一样,我们也可以使用 forEach 循环遍历关联数组。普通数组的属性和方法在关联数组上均可用,这是一个非常强大的工具。

