After a click on the button, there should be a randomly generated alphabet shown at the top, and a table of alphabets below, in either ascending or descending order.
If the index of the top alphabet in the array alphabets
is an even number, the order of the table below should be ascending. Take ‘f’ as an example of the top alphabet, the order in the table should go like, from left to right, ‘g’ -> ‘h’ -> ‘i’ -> ‘j’ -> ‘k’ -> ‘a’ -> ‘b’ -> …
If that index is an odd number, then the order of the table should be descending. With the same example, ‘f’ at the top, the table below should go like, again from left to right, ‘e’ -> ‘d’ -> ‘c’ -> ‘b’ -> ‘a’ -> ‘k’ -> ‘j’ -> …
I’d like to ask that, how to change my piece of code of the for loop in JS, in order to achieve such an effect?
const alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'];
const random = document.getElementById('random');
let display = document.getElementsByClass('display');
function click() {
var num = Math.floor(Math.random() * 11);
random.innerHTML = alphabets[num];
if (num % 2 = 0) {
for (let a = 0; a < 12; a++) {
display[a].innerHTML = alphabets[(a + num) % 12];
}
} else {
for (let a = 0; a < 12; a++) {
for (let b = 0; b > -12; b--) {
display[a].innerHTML = alphabets[(b - num) + 12];
}
}
}
}
div h1, div h6, div table tr td {
color: black;
}
<div>
<button onclick='click()'>Generate!</button>
<h1>Random Alphabet: </h1>
<h6 id="random"></h6>
</div>
<div>
<h1>Display: </h1>
<table>
<tr>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
<td class="display"></td>
</tr>
</table>
</div>