简体   繁体   English

Javascript:将数据分配给多维数组

[英]Javascript: assigning data to Multidimensional array

I am trying to convert Java code to Javascript and I am trying to assign data to 3 dimensional array and I am getting "TypeError: can't convert undefined to object " error. 我正在尝试将Java代码转换为Javascript,并试图将数据分配给3维数组,并且出现“ TypeError:无法将未定义的对象转换为对象”错误。 Following is my code. 以下是我的代码。 Thanks in advance for any help. 在此先感谢您的帮助。

var initData = [[2], [12], [2]];

for (var i = 0; i < 12; i++)
{
    initData[0][i][0] = -1;
    initData[0][i][1] = -1;
    initData[1][i][0] = -1;
    initData[1][i][1] = -1;
}
 [[2], [12], [2]]; 

That's not a declaration of dimensions, that's four array literals . 那不是维度的声明,而是四个数组文字 There are no multidimensional arrays in JS. JS中没有多维数组。 They're just one-dimensional lists that can contain arbitrary values (including other lists). 它们只是一维列表,可以包含任意值(包括其他列表)。

To create and fill an array that contains other arrays you have to use the following: 要创建并填充包含其他数组的数组,必须使用以下命令:

var initData = []; // an empty array
for (var i = 0; i < 2; i++) {
    initData[i] = []; // that is filled with arrays
    for (var j = 0; j < 12; j++) {
        initData[i][j] = []; // which are filled with arrays
        for (var k = 0; k < 2; k++) {
            initData[i][j][k] = -1; // which are filled with numbers
        }
    }
}

or, to apply your loop unrolling : 或者,应用循环展开

var initData = [[], []]; // an array consisting of two arrays
for (var i = 0; i < 12; i++) {
    // which each are filled with arrays that consist of two numbers
    initData[0][i] = [-1, -1];
    initData[1][i] = [-1, -1];
}

initData is a list of three lists, [2], [12] and [2]. initData是三个列表的列表,分别为[2],[12]和[2]。 Each one with one element. 每个一个元素。

In order to init a list(or array), you must do 为了初始化一个列表(或数组),您必须

var initData = [];

Then store in initData another list, like initData[0] = [] and so on... like it's mentioned, arrays/lists in javascript aren't initialized with a limit size. 然后将另一个列表存储在initData中,例如initData[0] = []等等,就像上面提到的那样,javascript中的数组/列表未使用限制大小进行初始化。

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

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