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>
Heretic Monkey
12.2k7 gold badges63 silver badges133 bronze badges
asked Nov 6, 2020 at 14:04
med benzekri
6037 silver badges19 bronze badges
2 Answers 2
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);
answered Nov 6, 2020 at 14:09
Esteban MANSART
5613 silver badges12 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Nathan Chu
OP means Math.random()*2. Math.random takes 0 arguments. MDN
Esteban MANSART
Yep, i just copied his code and didn't noticed this, i edited
Heretic Monkey
Are you sure
floor and random are not provided by p5.js? Because there are no errors in the snippet...Esteban MANSART
GJ i didn't see P5 include
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)
Comments
default
lengthnotlenghtarr.length.