1.类型[]
let arr1: number[] = [1, 2, 3]
let arr2: string[] = ['a', 'b', 'c']
let arr3: (number | string)[] = [1, 'a', 2, 'b']
2.Array<类型> 数组泛型
let arr4: Array<number> = [1, 2, 3]
let arr5: Array<string> = ['a', 'b', 'c']
let arr6: Array<number | string> = [1, 'a', 2, 'b']
3、用接口表示数组
interface NumberArray {
[index: number]: number
}
let arr7: NumberArray = [1, 2, 3]
4、arguments类数组
错误定义
function Arr(...args:any): void {
console.log(arguments)
//错误的arguments 是类数组不能这样定义
let arr:number[] = arguments
}
正确定义
function Arr(...args: any): void {
console.log(arguments)
// ts内置对象IArguments 定义
let arr: IArguments = arguments
}
其中 IArguments 是 TypeScript 中定义好了的类型
function sum() {
let args: IArguments = arguments
}
// 它实际上就是:
function sum() {
let args: {
[index: number]: any;
length: number;
callee: Function;
} = arguments
}
5、元组 Tuple
let tom: [string, number] = ['Tom', 25]
// tom[0] = 100 //错误
tom[1] = 100 //正确
// tom[2] = 'male' //错误
// tom[3] = true //错误
// 当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型:
let tom1: [string, number] = ['Tom', 25]
tom1.push('male')
tom1.push(true) //越界元素只能是string或number类型
6、多维数组
let arr8: number[][] = [[1, 2], [3, 4]]
let arr9: (number | string)[][] = [[1, 'a'], [2, 'b']]
let arr10: (number | string)[][][] = [[[1, 'a'], [2, 'b']], [[3, 'c'], [4, 'd']]]
7、any 在数组中的应用
let list: any[] = ['xcatliu', 25, { website: 'http://xcatliu.com' }]标签:typescript,string,--,number,let,arguments,数组,any From: https://www.cnblogs.com/zhuangdd/p/18588090
list[1] = 'string'
list.push(100)
list.push({ name: 'Tom' })
list.push([1, 2, 3])