Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The following code results in the console printing "Z".

<script>
var x = new Array(new Array());
x[0][0] = "Z";
console.log(x[0][0]);
</script>

But if I replace x[0][0] = "Z" with a nested for loop of arbitrary dimensions ...

<script>
var x = new Array(new Array());
for(i=0;i<5;i++){
    for(j=0;j<3;j++){
        x[i][j] = "Z";
    }
}
console.log(x[0][0]);
</script>

... it gets stuck on the very zeroth iteration, despite that being the same instruction (as far as I see) as given in the first one. According to both Chrome and Firefox output, it suddenly considers x[0][0] to be undefined.

What's the deal?

share|improve this question
1  
I think the first iteration is fine, but x[1][0] will throw an error, since your outer array only has one element. –  Felix Kling Nov 18 '13 at 2:50
add comment

1 Answer

up vote 0 down vote accepted

JavaScript doesn't have 2D arrays. What you can do is create an array of arrays. In your example you did exactly that, you created an array which contains another array.

var x = new Array(new Array());
console.log(x.length); // 1
console.log(x[0]); // []

x is an array with one element which happens to be an array. If you are trying to access x[1], i.e. the second element in the array, you will get an error because such element does not exist:

console.log(x[1]); // undefined

What you have to do is assign an array to the ith position in the outer array first:

var x = []; // create outer array
for(i=0;i<5;i++){
    x[i] = []; // create inner array at i
    for(j=0;j<3;j++){
        x[i][j] = "Z";
    }
}
console.log(x[0][0]);
share|improve this answer
    
Ah, that makes sense. I knew it was really an array of arrays, but I wasn't properly understanding the ways that made it fundamentally different from a regular array. –  Lenoxus Nov 18 '13 at 3:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.