二维数组初始化的三种方式(Three Ways to Initialize a 2D Array)

Three Ways to Initialize a 2D Array

Initializing a 2D array is a fundamental part of programming. There are many ways to initialize an array, but in this article, we will explore three different methods:

Method #1: Using a Nested Loop

One way to initialize a 2D array is to use a nested loop. This method involves using two for-loops to iterate through each row and column of the array and assign a value to each element:

```html ```

In the above code, we create a 2D array `arr` with three rows and three columns. We then use two for-loops to iterate through each row and column of the array. Inside the inner loop, we assign a value to each element using the formula `i * j`. Finally, we output the elements to the screen using the `document.write()` function.

Method #2: Using Array.from()

Another way to initialize a 2D array is to use the `Array.from()` method, which allows us to create an array from an array-like object, such as a string or another array. Here's an example:

```html ```

In the above code, we create a new array `arr` using the `Array.from()` method. The first argument `{length: 3}` specifies the length of the array, and the second argument is a callback function that creates and returns a new array with three zeros. We then output the elements to the screen using the same nested loop as before.

Method #3: Using Array.fill()

The third method we will explore is using the `Array.fill()` method to fill the 2D array with a predetermined value. Here's an example:

```html ```

In the above code, we create a new array `arr` using the `new Array(3).fill(0)` method to create a new array with three zeros. We then use the `Array.fill()` method to fill the 2D array with this new array. Finally, we output the elements to the screen using the same nested loop as before.

Conclusion

These are just three of the many ways to initialize a 2D array in JavaScript. Whether you use a nested loop, `Array.from()`, or `Array.fill()`, the key is to choose the method that best fits your needs and coding style. With these examples, you should be able to start experimenting with your own 2D arrays in your JavaScript code.

本文内容来自互联网,请自行判断内容的正确性。若本站收录的内容无意侵犯了贵司版权,且有疑问请给我们来信,我们会及时处理和回复。 转载请注明出处: http://www.ziy123.com/jfss/6926.html 二维数组初始化的三种方式(Three Ways to Initialize a 2D Array)