I am new to Javascript and am making a memory game but i can't seem to get this code to work. What i am trying to do is choose a random element from my ids array and then remove it from that array but be able to use that value afterwards to assign it to an element in the cards array. What I came up with so far is this (updated):
const cards = document.querySelectorAll(".memory-card");
let ids = ["1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6"];
function idHandler() {
let rand = Math.floor(Math.random() * ids.length);
let x = ids.splice(rand, 1)[0];
cards[x].setAttribute("id", x);
}
cards.forEach(mapIds);
Since someone asked for the html elements:
<div class="memory-card" id="1">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="1">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="2">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="2">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="3">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="3">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="4">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="4">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="5">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="5">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="6">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="6">
<img src="../assets/turned.png" class="front-face">
</div>
splice(), the deleted element(s) are returned, so you can save them into a variable for use later.let removedItem = ids.splice(randomValue, 1);xwill not always be-1with that code, although it will be quite a large proportion of the time. This is because you're trying to find the index in that array of a randomly-selected index from that array - the indices go from 0 to 11 and only"1"to"6"are present in the array. (I also have no idea why you are storing them as strings rather than numbers.)xwas being calculated, and since that was clearly wrong, as well as what the OP was drawing attention to, I didn't see the need to look further before making my comment