首页 资源列表 文章列表

typescript 数组添加数组

在 TypeScript 中,如果你想要将一个数组添加到另一个数组中,你可以使用几种不同的方法。以下是几种常见的方法来实现这个目标:


方法 1:使用扩展运算符(Spread Operator)

扩展运算符可以让你将一个数组的所有元素添加到另一个数组中。


let array1 = [1, 2, 3];

let array2 = [4, 5, 6];

// 使用扩展运算符

let combinedArray = [...array1, ...array2];

console.log(combinedArray); // 输出: [1, 2, 3, 4, 5, 6]


方法 2:使用 concat() 方法

concat() 方法用于合并两个或多个数组。这个方法不会改变现有的数组,而是返回一个新数组。


let array1 = [1, 2, 3];

let array2 = [4, 5, 6];

// 使用 concat 方法

let combinedArray = array1.concat(array2);

console.log(combinedArray); // 输出: [1, 2, 3, 4, 5, 6]


方法 3:使用 push() 方法结合扩展运算符

如果你想要在添加元素的同时修改原数组,可以使用 push() 方法结合扩展运算符。


let array1 = [1, 2, 3];

let array2 = [4, 5, 6];

// 使用 push 方法结合扩展运算符

array1.push(...array2);

console.log(array1); // 输出: [1, 2, 3, 4, 5, 6]


方法 4:使用 Array.prototype.forEach 或 for 循环

如果你想要在添加元素的同时有更复杂的逻辑,可以使用循环。


let array1 = [1, 2, 3];

let array2 = [4, 5, 6];

// 使用 forEach 方法

array2.forEach(item => array1.push(item));

console.log(array1); // 输出: [1, 2, 3, 4, 5, 6]

0.231397s