I am trying to understand why my code does not function as expected. This code I am running in a snippet in the browser:
function generateMaze(n) {
// let n = document.getElementById("maze-size").value;
let maze = [];
for (let i = 0; i < n; i++) {
let mazeWidth = new Array(n)
.fill(1)
.map((x) => (Math.random() >= 0.3 ? 1 : 0));
maze.push(mazeWidth);
}
console.log(maze);
}
console.log(generateMaze(5))
In the webpage I have the html: The only thing that differs here is that there is these 2 lines above the function to get the value and pass it to the function. I will include the full index.js at the end
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title></title>
</head>
<body>
<div>
<label htmlFor="maze-size">Input desired Maze Size</label>
<input id="maze-size" name="mazesize" type="text" />
<button id="generateMaze">
<p id="mazearea"></p>
Generate
</button>
</div>
</body>
<script src="index.js"></script>
</html>
index.js
"use strict";
const button = document.getElementById("generateMaze");
button.addEventListener("click", generateMaze);
function generateMaze() {
let n = document.getElementById("maze-size").value;
let maze = [];
for (let i = 0; i < n; i++) {
let mazeWidth = new Array(n)
.fill(1)
.map((x) => (Math.random() >= 0.3 ? 1 : 0));
maze.push(mazeWidth);
}
}
Summary is: This works perfectly as a standalone function generating a matrix 2d array with the defined input:
eg:
[
[0, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 0],
[1, 1, 0, 1, 1],
[0, 0, 1, 1, 1],
]
but when I use this function attached to a button I get an output of only 1 element in n number of arrays and I do not understand why.
Thank you in advance for any help you can provide.