简体   繁体   English

在JS中将2个数组添加到新数组

[英]adding 2 arrays to a new array in JS

I'm having difficulty adding arrays into another array without it merging all of the items inside of the array together. 我很难将数组添加到另一个数组中而不将数组内部的所有项目合并在一起。 I've tried push and concat and they don't seem to do what I'm looking for. 我已经尝试过推入和连接,但它们似乎并没有满足我的要求。

var a = [1,2,3]

var b = [4,5,6]

result = [[1,2,3],[4,5,6]]

Define your new array based on your current variables like this: 根据当前变量定义新数组,如下所示:

var a = [1,2,3];
var b = [4,5,6];

var result = [a,b]; //Creates [[1,2,3],[4,5,6]]

Can't you simply add to an another array? 您不能简单地添加到另一个数组吗?

Ie var result = []; result.push(a); result.push(b); var result = []; result.push(a); result.push(b); var result = []; result.push(a); result.push(b);

Or just declare it as such: 或者只是这样声明:

 result = [a,b]

This should do the trick: 这应该可以解决问题:

var a = [1,2,3]

var b = ["a","b","c"]

result = [a,b] // [[1,2,3],["a","b","c"]] 

With Fiddle . 小提琴

use this way: 使用这种方式:

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

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

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