Issue
So, I am trying to make a memory game and I want my function "CompareValue" to remember the last variable I passed I declared in the script at the beginning MemOne and MemTwo so they are global variables. Here is my HTML code :
function Start(){
var Cartes = [];
const listes_value = [1,2,3,4,5,6,7,8];
const randomvalue = [...listes_value, ...listes_value].sort(() => Math.random() - 0.5);
Cartes.push(
<center key={`row`}>
<div style={{ display: "flex", justifyContent: "center", margin: "20px 0" }}>
<div style={{ marginRight: "5px" }}>
<img src={img} onClick={() => CompareValue(randomvalue[1])} />
</div>
<div style={{ marginRight: "5px" }}>
<img src={img} onClick={() => CompareValue(randomvalue[2])} />
</div>
<div style={{ marginRight: "5px" }}>
<img src={img} onClick={() => CompareValue(randomvalue[3])} />
</div>
<div>
<img src={img} onClick={() => CompareValeur(randomvalue[4])} />
</div>
</div></center>
Here is my CompareValue function
function CompareValeur(value){
console.log("value :",value)
console.log("MemOne :",MemOne)
console.log("MemTwo :",MemTwo)
if (pair % 2 === 0) {
var MemOne = value
console.log("MemOne defined")
pair++;
} else {
var MemTwo = value
console.log("MemTwo defined")
pair++;
}
if (MemOne== MemTwo) {
console.log("Success !");
}
return MemTwo, MemOne}
Basically what I want my code to do is remember MemOne, and then compare it to MemTwo when another picture is clicked. But it seems that my function forget my variables at the very moment I return them
var MemOne = 0; //Global variable
var MemTwo = 1; //Global variable
var pair = 0; //Global variable
Here is how I define them at the beginning of my script. Pair is however not lost but I dont' understand why
Solution
You're redeclaring a variable inside an if scope.
var MemOne = value => MemOne = value
Reassign, not redeclare
Answered By - Odri
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.