JS: Arrays
Theory: Nested arrays
A value in an array can be anything, including another array. You can create an array in an array like this:
Each element, which is an array, is treated as a single unit. This can be seen from the size of the second array. JavaScript syntax allows you to place the elements of a created array line by line, let's rewrite the creation of the second array for clarity:
Nesting is not limited in any way. You can create an array of arrays of arrays and so on.
Accessing nested arrays looks a bit unusual, though logical:
You may not always be able to see exactly how to get to the right element when you're not used to it, but it's just a matter of practice:
Changing and adding arrays to an array:
Nested arrays can be modified directly by simply accessing the desired element:
The same goes for adding a new item:
So, what do we need nested arrays for? There are quite a few such examples, such as mathematical concepts like matrices, and representations of game boards. Remember tic-tac-toe? This is a similar case:
Let's look at a problem like this. If given a tic-tac-toe board. You need to write a function that checks if there is at least one cross or zero on this field, depending on what you are asked to check.
Now let's implement a function that performs the check:
Let's check it out:
Recommended programs
Completed
0 / 22

