多维数组拼接返回嵌套数组javascript



我有2个2D数组,希望将a[0]与b[0]合并

var a=[["a","b","c"],["d","e","f"]];
var b=[["1","2","3"],["4","5","6"]];
console.log(a[0].splice(1,2,b[0]));
its return ["a",["1","2","3"]]
i need to archive ["a","1","2","3"] for a[0]

任何一个身体都能表现出怎样?

docs,Array.splice的语法为

array.splice(start[,deleteCount[,item1[,item2[,…]]](

如您所见,您可以向数组中添加1个以上的元素,例如arr.splice(0,0,4,5),其中您将向数组中增加2个值(4&5(。使用b[0]作为第三个参数,可以在特定索引处添加整个数组。若要添加单个值,您需要分散数组的值。您可以使用排列语法。arr.splice(0,0,...[1,2])将成为arr.splice(0,0,1,2)

var a=[["a","b","c"],["d","e","f"]];
var b=[["1","2","3"],["4","5","6"]];
a[0].splice(1,2,...b[0])
console.log(a[0]);

您可以使用排列语法

Spread语法允许iterable在0+需要参数。

var a=[["a","b","c"],["d","e","f"]];
var b=[["1","2","3"],["4","5","6"]];
//if you are trying to achieve all elements in single array then
var result = [...a[0], ...b[0]];
console.log(result);
//if you are trying to achieve single element from first array and all from other then
var result = [...a[0][0], ...b[0]];
console.log(result);

关于Spread语法的好文章

最新更新