I am trying to write something that takes the array "words", shuffles it, and then inserts the different items from that shuffled array into my cards. The shuffling works fine but I get a "TypeError: cards[i] is undefined" when trying to run it. The array I'll use in the end contains 187 items, I have removed most of them from it to make the code shorter to post here.
Thanks in advance :)
jsfiddle: https://jsfiddle.net/storm273/1a4p2xLg/1/
the sketch.js:
var seed = 1;
var cards = document.getElementsByClassName('card');
console.log('cards', cards);
function shuffle(array, seed) {
var currentIndex = array.length, temporaryValue, randomIndex;
seed = seed || 1;
var random = function () {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
};
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
shuffle(words, seed);
console.log('words', words);
for (i = 0; i < 25; i++) {
console.log("loop");
cards[i].innerHTML = words[i];
}
the index.html:
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Codenames</title>
<link rel="stylesheet" href="styles.css" />
<script src="sketch.js"></script>
<script src="bundle.js"></script>
</head>
<body>
<div class="game">
<div class="board">
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
<div class="card">Word</div>
</div>
</div>
</body>
</html>```
` tag. There the "cards" are already parsed by the browser and therefor available in your script.
– Andreas Apr 03 '20 at 15:37