[英]Add array to two-dimensional array
Array A is a two dimensional array. 阵列A是二维阵列。 It's made up of array X and Y. I'd like to add array Z to Array A as another item in Array A. How do I do this? 它由数组X和Y组成。我想将数组Z添加到数组A作为数组A中的另一项。我该怎么办?
Edited to add code: 编辑添加代码:
arrayA = new Array(
[1, 2, 3] //array x
[4, 5, 6] //array y
);
arrayZ = new Array(7, 8, 9);
//now, how do I add arrayZ onto the end of arrayA?
This will add it to the end of arrayA 这会将它添加到arrayA的末尾
arrayA.push(arrayZ);
Here's a reference for push
: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push 以下是push
的参考: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push
You could push your arrays onto Array a
like so 您可以将阵列推送到Array a
var a = new Array();
var x = new Array();
var y = new Array();
var z = new Array();
a.push(x);
a.push(y);
a.push(z);
Edit: After OP edited question with code example: 编辑: OP编辑后的问题与代码示例:
var z = new Array(7, 8, 9);
var a = new Array(
[1, 2, 3],
[4, 5, 6]
);
a.push(z);
Without any code I am just assuming 没有任何代码,我只是假设
arr[0] = is array X arr [0] =是数组X.
arr[1] = is array Y arr [1] =是数组Y.
so you can use arr[2] for Y 所以你可以使用arr [2]代表Y.
var foo = new Array()
foo[0] = new Array() // Your x
foo[1] = new Array() // Your y
foo[2] = new Array() // Your z
Ok, lots of responses as to how to add items to arrays, but lets start with making your code better: 好的,关于如何将项添加到数组的许多响应,但让我们开始使您的代码更好:
arrayA = [ //don't use new Array()
[1, 2, 3],
[4, 5, 6]
];
arrayZ = [7,8,9];
There're a few ways you can do this. 有几种方法可以做到这一点。
You can use the array methods unshift or push 你可以使用数组方法unshift或push
arrayA.unshift(arrayZ) //adds z to the front of arrayA
arrayA.push(arrayZ) //adds z to the end of arrayA
You can also set the location explicitly: 您还可以明确设置位置:
arrayA[0] = arrayZ //overwrites the first element
arrayA[1] = arrayZ //overwrites the second element
arrayA[2] = arrayZ //adds a new element at 2
arrayA[arrayA.length] = arrayZ //essentially the same as using push
You can also splice the new element into the array: 您还可以将新元素拼接到数组中:
arrayA.splice(1, 0, arrayZ)
1
specifies the start index of the elements being inserted/removed . 1
指定要插入/移除的元素的起始索引。 0
specifies how many elements should be removed, in this case we're adding and not removing any. 0
指定应删除多少元素,在这种情况下,我们添加而不删除任何元素。 arrayZ
is the element to insert arrayZ
是要插入的元素
On ES6 you can use the spread operator ( ...
) as follows: 在ES6上,您可以使用扩展运算符( ...
),如下所示:
arrayA = [
[1, 2, 3],
[4, 5, 6]
];
arrayB = [7,8,9];
arrayA = [...arrayA, ...[arrayB]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.