概论
代码测试
// 普通数组
let uuy:Array<number>;
uuy=[23,23423,23423423]
let uud:[]
// let uua:array; //报错,不能这样声明数组
//从右往左是越子级内容
let uuv:number[][] //二维数组
uuv=[[23,23423,23423423],[23,23423,23423423],[23,23423,23423423]]
let uuo:Array<number>[]
uuo=[[23,23423,23423423],[23,23423,23423423],[23,23423,23423423]]
let uup:object[]
uup=[[23,23423,23423423],[23,23423,23423423],[23,23423,23423423]]
uup=[{a:23,b:23423,c:234}]
// in 只能用于映射类型且只能用于对象的key 映射,如下方式使用
let uum:{[k in ('a' | 'b' | 'c')]:any}[]
uum=[{a:23,b:23423,c:23}]
type UunKey="a" | "b" | "c"
let uun:{[k in UunKey]:any}
/**
* let uun: {
a: any;
b: any;
c: any;
}
*/
uun={
a:23,
b:23423,
c:234
}
// k in string 代表任意字符类型都可以作为key
let uui:{[k in string]:any}
uui={
a:23,
b:23423,
c:234,
d:3234234
}
let uuh:{[k in number]:any}
uuh={
0:23,
1:23423,
2:234,
3:3234234
}
let uuq:{[k:number]:string | number | symbol}
uuq={
0:23,
1:23423,
2:234,
3:3234234
}
/**
* 元组只能固定长度,且每个元素类型都要声明
*/
//元组数组
let uuc:[string,number,boolean];
uuc=["a",23,true]
// 1. 使用方括号语法
let numbers1: number[] = [1, 2, 3, 4, 5];
// 2. 使用泛型数组类型
let numbers2: Array<number> = [1, 2, 3, 4, 5];
// 3. 使用 Array 构造函数
let numbers3: number[] = new Array(1, 2, 3, 4, 5);
let emptyArray: any[] = new Array();
// 4. 使用 Array.of 方法
let numbers4: number[] = Array.of(1, 2, 3, 4, 5);
let mixedArray1: any[] = Array.of(1, "a", true);
// 5. 使用 Array.from 方法
let arrayLike: number[] = Array.from({ length: 5 }, (_, index) => index + 1);
let set: Set<number> = new Set([1, 2, 3]);
let numbers5: number[] = Array.from(set);
// 6. 使用类型断言
let mixedArray2 = [1, "a", true] as (number | string | boolean)[];
let strings = ["a", "b", "c"] as string[];
// 7. 创建多维数组
let twoDimensionalArray: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let threeDimensionalArray: number[][][] = [
[
[1, 2, 3],
[4, 5, 6]
],
[
[7, 8, 9],
[10, 11, 12]
]
];
// 8. 使用 ReadonlyArray 类型
let readonlyNumbers: ReadonlyArray<number> = [1, 2, 3, 4, 5];
前端工程师、程序员