在本教程中,我们将通过实例来学习如何在TypeScript中组合两个或多个数组。
在TypeScript中,有很多方法来组合数组,让我们来学习最常用的数组组合方法。
使用扩展运算符
为了将两个数组合并成一个数组,我们可以使用TypeScript中的es6 spread(...)操作符。
下面是一个例子。
const num1 = [1, 2];
const num2 = [3, 4];
console.log([...num1,...num2]);
输出。
[1, 2, 3, 4]
注意:spread(...)操作符将迭代器(如集合、数组、对象等)解压成一个个单独的元素。
使用Array.Concat( )方法
我们可以使用内置的Array.concat() 方法来组合TypeScript中的数组。
Array.concat() 方法将一个或多个数组作为参数,并通过组合返回新的数组。它不会改变现有的数组。
下面是一个例子。
const num1 = [1, 2];
const num2 = [3, 4];
const result = num1.concat(num2);
console.log(result);
合并三个数组
const num1 = [1, 2];
const num2 = [3, 4];
const num3 = [5, 6];
console.log(num1.concat(num2,num3));
输出。
[1, 2, 3, 4, 5, 6]