'I was creating an simon game using javascript but i got an error on console:
Please give me the solution for this code I was creating an simon game using javascript but i got an error on console:
The error: Uncaught ReferenceError: randomChosenColour is not defined at game.js:3:20 (anonymous) @ game.js:3
index.html file code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div lass="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="game.js"></script>
</body>
</html>
game.js code:
var buttonColours = ["red", "blue", "green", "yellow"];
var gamePattern = [randomChosenColour];
function nextSequence(params) {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColours[randomNumber];
gamePattern.push(randomChosenColour);
}
Solution 1:[1]
It is because by the time you declare gamePattern, randomChosenColour is not defined yet.
You just need to declare the gamePattern array to be an empty array.
var gamePattern = [];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | holydragon |
