简体   繁体   English

Javascript创建多维数组

[英]Javascript create multidimensional array

I try to create a 4-dimensional array. 我尝试创建一个4维数组。 I fill it dynamically and use content of it in another function. 我动态地填充它,并在另一个函数中使用它的内容。 But the content is empty. 但是内容为空。 Is there error below code? 代码下方是否有错误?

    var datas = []; // day number of a week
    for(var i = 0; i < 7; i++) {
            var size = 24*60/timeInterval;
            datas[i] = [];

            for(var j = 0; j < size; j++) {
                var size2 = allCoords.length / 2;
                datas[i][j] = [];

                for(var k = 0; k < size2; k++) {
                    datas[i][j][k] = [];
                }
            }
        }

I test below example : 我测试以下示例:

function foo1()
{
    datas[0][0][0].push(10);
}

function foo2()
 {

     document.getElementByID('result').innerHTML = datas[0][0][0];
 }

I see only ,,,,,,, . 我只能看到,,,,,,,

I think the principal problem is that you're getting the element where you want to show your result badly using getElementByID instead of getElementById . 我认为主要的问题是,你得到你想要展现你的结果不好使用元素getElementByID代替getElementById Also make sure that your element has innerHTML property to write the result, or alternatively use value . 还要确保您的元素具有innerHTML属性以写入结果,或者使用value

I write the follow example using <textArea id="result"></textArea> and generating a button which calls foo1();foo2(); 我使用<textArea id="result"></textArea>编写以下示例,并生成一个调用foo1();foo2();的按钮foo1();foo2(); onClick an it works for me. onClick对我onClick

In the sample I use an random value for timeInterval and allCoords.length . 在示例中,我为timeIntervalallCoords.length使用随机值。

Note also that you want a 4-dimensional array however you're creating a 3-dimensional. 还要注意,您需要一个4维数组,但是要创建3维数组。

 var timeInterval = 60; var allCoords = { length : 1}; var datas = []; // day number of a week for(var i = 0; i < 7; i++) { var size = 24*60/timeInterval; datas[i] = []; for(var j = 0; j < size; j++) { var size2 = allCoords.length / 2; datas[i][j] = []; for(var k = 0; k < size2; k++) { datas[i][j][k] = []; } } } function foo1() { datas[0][0][0].push(10); } function foo2() { document.getElementById('result').value = datas[0][0][0]; } 
 <textArea id="result"></textArea> <input type="button" value="foo" onclick="foo1();foo2();"/> 

Hope this helps, 希望这可以帮助,

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

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