Reputation: 603
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/[email protected]/lib/p5.min.js"></script>
<script type="text/javascript" src="gol.js"></script>
</head>
<body>
</body>
</html>
Upvotes: 0
Views: 77
Reputation: 677
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)
Upvotes: 0
Reputation: 561
You made 2 mistakes : one the 3rd line, this is not arr.length
that you want but cols
Then, floor and random are parts of the Math lib provided by JS, so use it like this:
arr[i][j] = Math.floor(Math.random() * 2);
Upvotes: 1