[英]creating 2d array in JavaScript
我是 js 的新手並試圖創建一個 2D 數組,但是當我運行代碼時,我進入了控制台Array(10) [ <10 empty slots> ]
即使我用值填充了數組。
這是我的 js 和 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);
我不確定你想用floor(random(2))
部分做什么,但你可以創建如下二維數組:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.