JavaScript: How to create and use two dimensional Arrays
Question by Compi | 2015-08-13 at 13:53
In JavaScript, you can create a normal one-dimensional array without any problems by using the following way.
var arr = [1, 2, 3, 4];
But what about multidimensional arrays in JavaScript? In my case, I would like to create a two-dimensional array.
Does JavaScript support 2-dimensional arrays at all? And if yes, can someone tell me the exact syntax of declaring such arrays and how it is possible to access the elements?
Related Topics
JavaScript: Create and Use Arrays
Info | 0 Comments
PHP: Write array to individual Variables
Tutorial | 0 Comments
JavaScript: Create associative Arrays
Question | 1 Answer
jQuery: Scroll up and down with and without JavaScript
Tip | 0 Comments
JavaScript: Show and hide HTML area by clicking a link
Tutorial | 0 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
In order to create a two-dimensional array in JavaScript, you only have to define another array as an element of an existing array. For example in like that:
To access those elements, you can go like that:
Of course, when working with very large arrays, this notation has its difficulties. In such a case, it might be better to use the following initialization procedure:
Using new Array(), we are able to create a new array of a defined length. In the first line of the example, we are creating an array consisting of 100 elements. After that, we are looping through this array element for element and we are setting each element to another array consisting of 10 elements. Doing so, we are getting an array with 100 x 10 fields.
Of course, you can also access those fields via a loop.
Here, we are going through the array with two loops and we are setting each array element to the product of the first and the second loop variable.
All of the examples are referring to two dimensional arrays. But in the same way, we can also create arrays consisting of more dimensions - finally, each element of a two-dimensional array can be another array.
2015-08-13 at 17:06