简体   繁体   English

如何在javascript中连接两个锯齿状数组

[英]how to concatenate two jagged arrays in javascript

I have two arrays One is:我有两个数组一个是:

[ [ 2, 'c' ],
  [ 2, 'e' ],
  [ 3, 'a' ],
  [ 3, 'b' ] ]

and another is :另一个是:

[ 3, [ 1, 'g' ], [ 2, [ 1, 'd' ], [ 1, 'f' ] ] ]

how can I concatenate both and get output like我怎样才能连接两者并获得输出

[ [ 2, 'c' ],
  [ 2, 'e' ],
  [ 3, 'a' ],
  [ 3, 'b' ],
  [ 3, [ 1, 'g' ], [ 2, [ 1, 'd' ], [ 1, 'f' ] ] ]
var arr1 = [ [ 2, 'c' ],
             [ 2, 'e' ],
             [ 3, 'a' ],
             [ 3, 'b' ] ];  
var arr2 = [ 3, [ 1, 'g' ], [ 2, [ 1, 'd' ], [ 1, 'f' ] ] ];
arr1.push(arr2);

Have you tried using the spread operator?您是否尝试过使用扩展运算符? Please be aware that it's not supported in IE.请注意,它在 IE 中不受支持。

const x = 
    [ [ 2, 'c' ],
    [ 2, 'e' ],
    [ 3, 'a' ],
    [ 3, 'b' ] ];

const y = [ 3, [ 1, 'g' ], [ 2, [ 1, 'd' ], [ 1, 'f' ] ] ];

const z = [...x, y];

console.log(z);

You could wrap the additional array in extra brackets for use with Array#concat .您可以将额外的数组包装在额外的括号中以与Array#concat

 var a = [[2, 'c'], [2, 'e'], [3, 'a'], [3, 'b']], b = [3, [1, 'g'], [2, [1, 'd'], [1, 'f']]]; console.log(a.concat([b]));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

concat will merge two arrays into one array without changing the original arrays concat将两个数组合并为一个数组而不改变原始数组

Code代码

const x = 
    [ [ 2, 'c' ],
    [ 2, 'e' ],
    [ 3, 'a' ],
    [ 3, 'b' ] ]

const y = [ 3, [ 1, 'g' ], [ 2, [ 1, 'd' ], [ 1, 'f' ] ] ];

const z = x.concat([y])

Example例子

 const x = [ [2, 'c'], [2, 'e'], [3, 'a'], [3, 'b'] ] const y = [3, [1, 'g'], [2, [1, 'd'], [1, 'f'] ] ]; const z = x.concat([y]) console.log(z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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