目录
元组(Tuple)是固定数量的不同类型的元素的组合。
元组与集合的不同之处在于,元组中的元素类型可以是不同的,而且数量固定。元组的好处在于可以把多个元素作为一个单元传递。如果一个方法需要返回多个值,可以把这多个值作为元组返回,而不需要创建额外的类来表示。
- let arr:[number, string] = [1,'wang']
- console.log(arr); // [ 1, 'wang' ]
-
-
- let arr2: readonly [number,boolean,string,undefined] = [1,true,'sring',undefined]
- console.log(arr2); // [ 1, true, 'sring', undefined ]
当赋值或访问一个已知索引的元素时,会得到正确的类型:
- let arr:[number, string] = [1,'wang']
- console.log(arr); // [ 1, 'wang' ]
-
- console.log(arr[0].length); // 报错
- console.log(arr[1].length); // 4
-
- // 数字类型,没有长度
- let arr:[number,string] = [1,'string']
-
- arr.push(true) // 报错 arr里面没有boolean类型
红绿蓝 Red = 0 Green = 1 Blue= 2 分别代表红色0 绿色为1 蓝色为2
- enum Types{
- Red,
- Green,
- BLue
- }
- console.log(Types); // { '0': 'Red', '1': 'Green', '2': 'BLue', Red: 0, Green: 1, BLue: 2 }
- //默认就是从0开始的 可以不写值
- enum Types{
- Red = 0,
- Green = 1,
- BLue = 2
- }
- console.log(Types); // { '0': 'Red', '1': 'Green', '2': 'BLue', Red: 0, Green: 1, BLue: 2 }
增长枚举
- enum Types{
- Red = 1,
- Green,
- BLue
- }
- console.log(Types); // { '1': 'Red', '2': 'Green', '3': 'BLue', Red: 1, Green: 2, BLue: 3 }
我们定义了一个数字枚举, Red使用初始化为 1。 其余的成员会从 1开始自动增长。 换句话说, Type.Red的值为 1, Green为 2, Blue为 3。
字符串枚举的概念很简单。 在一个字符串枚举里,每个成员都必须用字符串字面量,或另外一个字符串枚举成员进行初始化。
- enum Types{
- Red = 'red',
- Green = 'green',
- BLue = 'blue'
- }
由于字符串枚举没有自增长的行为,字符串枚举可以很好的序列化。
枚举可以混合字符串和数字成员
- enum Types{
- No = "No",
- Yes = 1,
- }
-
- console.log(Types); // { '1': 'Yes', No: 'No', Yes: 1 }