cycle cyletic
cycle cyletic

Reputation: 67

Javascript create multidimensional array

I try to create a 4-dimensional array. 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 ,,,,,,,.

Upvotes: 0

Views: 314

Answers (1)

albciff
albciff

Reputation: 18507

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. Also make sure that your element has innerHTML property to write the result, or alternatively use value.

I write the follow example using <textArea id="result"></textArea> and generating a button which calls foo1();foo2(); onClick an it works for me.

In the sample I use an random value for timeInterval and allCoords.length.

Note also that you want a 4-dimensional array however you're creating a 3-dimensional.

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,

Upvotes: 1

Related Questions