0

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>

2
  • 1
    Typo, its length not lenght Commented Nov 6, 2020 at 14:06
  • At line 3 in the javascript portion, it should be arr.length. Commented Nov 6, 2020 at 14:07

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

OP means Math.random()*2. Math.random takes 0 arguments. MDN
Yep, i just copied his code and didn't noticed this, i edited
Are you sure floor and random are not provided by p5.js? Because there are no errors in the snippet...
GJ i didn't see P5 include
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.