CODING ACADEMY

View Original

How to Iterate through an Array using jQuery

As I was developing the latest course, Tic-Tac-Toe using jQuery, one of the things that had to be accomplished was to iterate through an array. It is an easy process but I thought it would be useful to go through the code.

See this content in the original post

In Line 3 we are declaring a variable called firstArray. It is an array that contains 4 elements.

What we need to do is iterate through each of those elements. To do this we can use the .each method as follows:

See this content in the original post

Line 5 uses the .each method and starts the iteration process on the array called firstArray.

For each element in the array we will be running a function.

Each element will have a key => value pair associated with it.

The key is the position in the array and the value is the actual content of the element in that position.

So, we add the key and value arguments to the function as follows:

See this content in the original post

Now that we are iterating through the array we can operate on each element in the array.

For this example, we shall simply write the key and value to the console as follows:

See this content in the original post

WANT TO LEARN MORE

Join the Tic-Tac-Toe using jQuery course. It takes the iteration a step further and looks at multidimensional arrays.

You can enroll in the course now.