7

Simply put, is there a way to create a 2D javascript array using similar syntax to this?

var newArray = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
]
2
  • What's the problem, doesn't it work like a charm ?-) Commented Oct 12, 2008 at 0:21
  • I didn't think to test it out, probably because it was 11pm and my bedtime is 10 ;) Commented Oct 12, 2008 at 11:17

3 Answers 3

12

You can create any n-dimensional arrays using exactly the format you suggest as in the following sample:

<script>
    var newArray = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]
    ]
    var newArray3d =
        [[[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8]],
         [[10, 11, 12],[13, 14, 15],[16, 17, 18]],
         [[20, 21, 22],[23, 24, 25],[26, 27, 28]]]
    alert(newArray[0]);
    alert(newArray[0][2]);
    alert(newArray3d[0]);
    alert(newArray3d[1][0]);
    alert(newArray3d[1][0][2]);
</script>

The alert boxes return, in sequence:

0,1,2
2
0,1,2,3,4,5,6,7,8
10,11,12
12
Sign up to request clarification or add additional context in comments.

Comments

2

Yes. This works fine:

<script>
var newArray = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
]
alert(newArray[0][2]);
</script>

Comments

2

Tested and working in FF3, Opera 9, IE6, and Chrome.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.