Array 类型
初始化
number[]、Array
二维: number[][]、Array
注意, 函数泛型在前,
(x: T)
let list: number[] = [1, 2, 3];
// ES5:var list = [1,2,3];
let list: Array<number> = [1, 2, 3]; // Array<number>泛型语法
// ES5:var list = [1,2,3];
Array<number | string> = [1, 2, 3, '4']
// 二维数组
let grid: number[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
数组解构
let x: number; let y: number ;let z: number;
let five_array = [0,1,2,3,4];
[x,y,z] = five_array;
数组展开运算符
let two_array = [0, 1];
let five_array = [...two_array, 2, 3, 4];
数组遍历
let colors: string[] = ["red", "green", "blue"];
for (let i of colors) {
console.log(i);
}
Set
let ans: Set<number> = new Set();
Tuple元祖
出现的意义:
更准确的约束数组元素
// 姓名,年龄, 收入
let userInfo: (number | string)[] = ['Jack', 18, '3500'];
// '3500'会错误提示
let userInfo: [string, number, number] = ['Jack', 18, '3500'];
什么是元祖:
数量有限,每项类型固定
使用场景:csv、excel导出文件数据转js时
// 元祖类型
const teacherInfo: [string, number, string] = ['Jack', 29, 'beijing']
// csv
const teacherList: [string, number, string][] = [
['Jack', 29, 'beijing'],
['Jack', 29, 'beijing'],
['Jack', 29, 'beijing'],
]
数组 VS 元祖
强类型转换
function person() {
const name: string = 'Jack';
const age: number = 24;
// return [name, age] as const;
return <const>[name, age];
}
const p1 = person();
const [name] = p1;
homework: 实现元祖转数组函数
function tuplify<T extends unknown[]>(elements: T): T {
return elements;
}
const userInfo: [string, number] = ['Jack', 11];
console.log(tuplify(userInfo));
// [ 'Jack', 11 ]