preface

How does JavaScript create a two-dimensional array? I came across a method that looked cool, but actually, there was a pitCopy the code

There are pit methods

The code looks like this:

var arr = new Array(10).fill(new Array(10).fill(0))
Copy the code

The console prints arR

At this point, if you want to set,arr[0][0] = 1, you’ll notice that the first entry in all the subarrays of a two-dimensional array is changed to 1

That’s the trick, you just want to change the first entry in the first subarray, but you change the first entry in all the subarrays at once

Refuse pit, start from honest code code

var a = new Array(a);for(var i=0; i<5; i++){// The one-dimensional length is 5

    a[i] = new Array(a);for(var j=0; j<5; j++){// The two-dimensional length is 5

    	a[i][j] = 0; }}Copy the code

The console prints a, and the output is as follows

Change a[0][0] = 1 and print a again, as shown below

Optimize the code

How do I make it easier to create a two-dimensional array? As shown below.

var arr = new Array(10); // The table has 10 rows
for(var i = 0; i < arr.length; i++){ arr[i] =new Array(10).fill(0); // Each row has 10 columns
}
Copy the code

Console output

To change thearr[0][0] = 1, print it againarr, the output is as follows

Achieved our expected results, the end of flower sprinkling ~~