简体   繁体   中英

creating 2d array in JavaScript

I am a newbie at js and trying to create a 2D array but when I run the code I get in the console Array(10) [ <10 empty slots> ] even though I filled the array with values.
This is my js and HTML:

 function Make2Darray(cols, rows) { let arr = new Array(cols); for (let i = 0; i < arr.lenght; i++) { arr[i] = new Array(rows); for (let j = 0; j < rows; j++) { arr[i][j] = floor(random(2)); } } return arr; } let grid; grid = Make2Darray(10, 10); console.log(grid);
 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Game of Life</title> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/p5@1.1.9/lib/p5.min.js"></script> <script type="text/javascript" src="gol.js"></script> </head> <body> </body> </html>

你犯了两个错误:第三行,这不是你想要的arr.length而是cols然后, floor 和 random 是 JS 提供的数学库的一部分,所以像这样使用它:

arr[i][j] = Math.floor(Math.random() * 2);

I am not sure what you are trying to do with floor(random(2)) part, but you can create 2D array as below:

 function Make2Darray(rows, cols) { let arr = [] for (let i = 0; i < rows; i++) { arr[i] = [] for (let j = 0; j < cols; j++) { arr[i][j] = Math.floor(Math.random()) // You can change the value in this part } } return arr } let grid = Make2Darray(10, 10) console.log(grid)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM