简体   繁体   中英

How to concat two javascript arrays?

I seem to have trouble to concat two javascript arrays. Here is the code:

console.log("\n\n");
a = [[1,2]];
b = [[1,2,3]];
console.table(a);
console.table(b);
a.concat(b);
console.table(a);

in which I create two arrays 'a' and 'b' (with elements being arrays as well, but who cares), with the goal of adding the single element of 'b' (the array [1,2,3] to the array 'a'. I expect 'b' to have two elements now (the array [1,2] and the array [1,2,3] , but it does not look so. I get the output as follows:

在此处输入图片说明

I expected the last output of console.table to have two rows with the content

0   1   2
1   1   2   3

What am I doing wrong here?

.concat不会改变原始数组,您必须重新分配:

a = a.concat(b);

concat() does not change the existing arrays, but returns a new array, containing the values of the joined arrays. you will have to assign it to some variable.

 console.log("\\n\\n"); a = [[1,2]]; b = [[1,2,3]]; console.log(a); console.log(b); console.log(a.concat(b)); 

Instead of manipulate an exisiting array a.concat(b) returns a new one.

you should try:

var c = a.concat(b)
console.table(c)

If you are using ES6 you can use the spread operator to get the desired result:

console.log("\n\n");
a = [[1,2]];
b = [[1,2,3]];
console.table(a);
console.table(b);
c = [...a, ...b];
console.table(c);

If arrays a and b have one element each then this will give you the answer

var c = a[0].concat(b[0]);

otherwise you would have to use a map or easily do it in ES6 with ...

If you are avoiding the reassignment, you could use Array.push.apply() :

 var a = [[1,2]], b = [[1,2,3]]; a.push.apply(a,b); console.log(a); 

Note: This was offered for completeness, my opinion would be to use concat assign as it's easier for me to understand what is occurring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM