1. 数组声明:
let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: string[] = ["apple", "banana", "orange"];
或者使用 Array 泛型:
let numbers: Array<number> = [1, 2, 3, 4, 5];
let fruits: Array<string> = ["apple", "banana", "orange"];
2. 访问数组元素:
let numbers: number[] = [1, 2, 3, 4, 5];
let firstNumber: number = numbers[0];
let secondNumber: number = numbers[1];
3. 修改数组元素:
let numbers: number[] = [1, 2, 3, 4, 5];
numbers[0] = 10;
numbers[2] = numbers[1] + numbers[2];
4. 数组方法:
let numbers: number[] = [1, 2, 3, 4, 5];
let length: number = numbers.length; // 获取数组长度
let sum: number = numbers.reduce((total, num) => total + num, 0); // 计算数组元素的和
let filteredNumbers: number[] = numbers.filter(num => num > 2); // 过滤数组元素
let mappedNumbers: number[] = numbers.map(num => num * 2); // 对数组元素进行映射
let sortedNumbers: number[] = numbers.sort((a, b) => a - b); // 对数组元素进行排序
console.log(length, sum, filteredNumbers, mappedNumbers, sortedNumbers);
5. 多维数组:
let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
6. 使用 for...of 循环遍历数组:
let numbers: number[] = [1, 2, 3, 4, 5];
for (let num of numbers) {
console.log(num);
}
7. 使用 forEach 方法遍历数组:
let numbers: number[] = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num));
这些是 TypeScript 中关于数组的一些基本用法。数组是一种常见的数据结构,对于存储和处理一组相同类型的数据非常有用。
转载请注明出处:http://www.zyzy.cn/article/detail/13017/TypeScript