javascript 在javascript中创建一个二维对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6510864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a 2d array of objects in javascript
提问by elssar
I have a javascript object -
我有一个 javascript 对象 -
cell{xPos, yPos};
I would like to create a 2d array of this object.
我想创建这个对象的二维数组。
cellPrototype = function(x, y) {
this.xPos = x;
this.yPos = y;
}
var cell = new Array();
for(var i=0;i<10;i++)
{
cell[i] = new Array();
for(var j=0;j<10;j++)
{
cell[i][j] = new cellPrototype(i,j);
}
}
This code doesn't work. Neither does -
此代码不起作用。也没有——
var cellPrototype = function(x, y) {
return {
xPos : x;
yPos : y;
}
var cell = new Array();
for(var i=0;i<10;i++)
{
cell[i] = new Array();
for(var j=0;j<10;j++)
{
cell[i][j] = new cellPrototype(i,j);
}
}
So how do I create a 2d array of an object in javascript?
那么如何在 javascript 中创建一个对象的二维数组呢?
回答by Robert
This works fine for me, I'm not sure if that's exactly the output you're looking for, where
Array[x][y]
will reference an object with points at x, y
.
这对我来说很好用,我不确定这是否正是您正在寻找的输出,在哪里
Array[x][y]
将引用带有x, y
.
var Coords = function(x, y) {
return {
"x" : x,
"y" : y
};
};
var Main = [];
for (var i = 0, l = 10; i < l; i++) {
Main[i] = [];
for (var j = 0, l2 = 10; j < l2; j++) {
Main[i][j] = Coords(i, j);
}
}
回答by Naftali aka Neal
You can make a 2d array like so:
您可以像这样制作二维数组:
var new_array = [];
var arr_length = 10;
for(var i = 0; i < arr_length; ++i){
new_array[i] = [];
}
回答by user819666
make an empty array and push the child arrays onto it
创建一个空数组并将子数组推到它上面
var array = [];
array.push([1,2,3,4]);
//array[0][0] == 1
or all in one shot
或一次性完成
var array = [[1,2,3,4], [1,2,3,4], [1,2,3,4]];
回答by danie7L T
This post is a bit old, but here is another way to create a 2D array
这篇文章有点旧,但这里有另一种创建二维数组的方法
var arr1=[];
var x=['a','b','c','d'];
var y=[1,2,3,4];
for( var i in x){
arr1.push([x[i],y[i]]); //For x and y of the same length
}
In JavaScript x and y can be objects arrays
在 JavaScript 中 x 和 y 可以是对象数组