TypeScript 元组
我们知道数组可以存储相同数据类型的多个值。但是有时候,我们可能需要在单个变量中存储不同数据类型的值的集合。数组不提供这个功能,但是TypeScript有一种叫做元组的数据类型来实现这个目的。元组是一个数组,可以存储属于不同数据类型的多个字段。它类似于C编程语言中的结构体。
元组是一种可以像其他变量一样使用的数据类型。它表示异构值的集合,并且还可以作为函数调用中的参数传递。
在抽象数学中,术语元组用于表示多维坐标系。JavaScript没有元组作为数据类型,但是元组在TypeScript中是可用的。元组中元素的顺序很重要。
语法
let tuple_name = [val1,val2,val3, ...val n];
示例1
let arrTuple = [101, "JavaTpoint", 105, "Abhishek"];
console.log(arrTuple);
输出:
[101, 'JavaTpoint', 105, 'Abhishek']
我们也可以在Typescript中将元组声明和初始化分开,首先将元组声明为空元组。
示例2
let arrTuple = [];
arrTuple[0] = 101
arrTuple[1] = 105
访问元组元素
我们可以通过使用索引来读取或访问元组的字段,索引与数组相同。在元组中,索引从零开始。
示例
let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
console.log("Name of the Employee is : "+empTuple [0]);
console.log("Age of the Employee is : "+empTuple [1]);
console.log(empTuple [0]+" is working in "+empTuple [2]);
输出:
Name of the Employee is: Rohit Sharma
Age of the Employee is: 25
Rohit Sharma is working in JavaTpoint
元组的操作
元组有两个操作:
- Push()
- Pop()
Push()操作
Push操作用于将元素添加到元组中。
示例
let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
console.log("Items: "+empTuple);
console.log("Length of Tuple Items before push: "+empTuple.length); // returns the tuple size
empTuple.push(10001); // append value to the tuple
console.log("Length of Tuple Items after push: "+empTuple.length);
console.log("Items: "+empTuple);
输出:
Items: Rohit Sharma, 25, JavaTpoint
Length of Tuple Items before push: 3
Length of Tuple Items after push: 4
Items: Rohit Sharma, 25, JavaTpoint, 10001
Pop()操作
弹出操作用于从元组中删除一个元素。
示例
let empTuple = ["Rohit Sharma", 25, "JavaTpoint", 10001];
console.log("Items: "+empTuple);
console.log("Length of Tuple Items before pop: "+empTuple.length); // returns the tuple size
empTuple.pop(); // removed value to the tuple
console.log("Length of Tuple Items after pop: "+empTuple.length);
console.log("Items: "+empTuple);
输出:
Items: Rohit Sharma,25, JavaTpoint, 10001
Length of Tuple Items before pop: 4
Length of Tuple Items after pop: 3
Items: Rohit Sharma, 25, JavaTpoint
更新或修改元组元素
元组是可变的,这意味着我们可以更新或更改元组元素的值。要修改元组的字段,我们需要使用字段的索引和赋值运算符。我们可以通过以下示例来理解。
示例
let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
empTuple[1] = 30;
console.log("Name of the Employee is: "+empTuple [0]);
console.log("Age of the Employee is: "+empTuple [1]);
console.log(empTuple [0]+" is working in "+empTuple [2]);
输出:
Name of the Employee is: Rohit Sharma
Age of the Employee is: 30
Rohit Sharma is working in JavaTpoint
清除元组的字段
我们无法删除元组变量,但可以清除其字段。要清除元组的字段,可以将其赋值为空集合的元组字段,如以下示例所示。
示例
let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
empTuple = [];
console.log(empTuple);
输出:
[]
解构元组
解构允许我们打破一个实体的结构。TypeScript在元组的上下文中使用解构。
示例
let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
let [emp, student] = empTuple;
console.log(emp);
console.log(student);
输出:
Rohit Sharma
25
向函数传递元组
我们可以将元组传递给函数,下面的示例中可以看到。
示例
//Tuple Declaration
let empTuple = ["JavaTpoint", 101, "Abhishek"];
//Passing tuples in function
function display(tuple_values:any[]) {
for(let i = 0;i
输出:
JavaTpoint
101
Abhishek