Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Print a 2D Array in JavaScript

Sep 28, 2024

If you have a 2D array in JavaScript and want to print its contents, you can use the console.log method along with nested loops. Here's a simple example of how to do it:

```javascript

const myArray = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

];

for (let i = 0; i < myArray.length; i++) {

for (let j = 0; j < myArray[i].length; j++) {

console.log(myArray[i][j]);

}

}

```

In this example, we have a 2D array called myArray with 3 rows and 3 columns. We use nested for loops to iterate through each element of the array and use console.log to print its value. When you run this code, you will see the following output in the console:

```

1

2

3

4

5

6

7

8

9

```

This technique can be applied to any 2D array, regardless of its size or content. By using nested loops, you can access each individual element of the array and print it to the console.

Another approach to print a 2D array is to use the Array.prototype.forEach method. Here's how you can do it:

```javascript

myArray.forEach(row => {

row.forEach(element => {

console.log(element);

});

});

```

In this example, we use the forEach method to iterate over each row of the array and then use another forEach method to iterate over the elements within each row. Again, you will get the same output when you run this code.

In conclusion, printing a 2D array in JavaScript is a straightforward process using console.log and nested loops or the forEach method. Whether you prefer the traditional for loops or the more modern forEach method, both approaches will allow you to easily display the contents of a 2D array. So next time you need to print a 2D array in your JavaScript code, give one of these methods a try and see how they work for you.

Recommend