简体   繁体   中英

Am I doing something wrong here?

I'm sorry if my question is very vague as i'm very very very new to coding and asking coding questions but i hope someone understands my problem as this is very frustrating because an error message doesn't appear but i don't know what im doing wrong.

So for context, i have a array number shuffler.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function shuffle(o) {
  for (let j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
};
let random = shuffle(numbers);

im trying to make a random number generator without repetition and im going to use those numbers to generate random images correlating to the number. So i set the first image to the first index of random

let setImgUrl = "img" + random[0] + ".jpg";

and now i want to make a button that shifts it to random[1] as a way to switch to the next random image.

let calcNewImg;
if (random[0]) {
  calcNewImg = random[1]
} else if (random[1]) {
  calcNewImg = random[2]
}

it'll keep repeating to random[9] (which is the last index) and the image appears like this

Img.setAttribute("src", "img/img" + calcNewImg + ".jpg");

when i click the button to switch to the next image, it works once and doesnt work the any other time with no error message. Hope i gave enough info that someone can understand, please feel free to ask for more info if it is needed. i really appreciate this help.

I think what you need is an infinite loop to generate the image Ids something like this

 button=document.getElementById("button") showimg=document.getElementById("showimg") button.addEventListener("click",getimg) let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function shuffle(o) { for(let j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; }; let random = shuffle(numbers); var i=0 function getimg(){ calcNewImg = random[i] i++ if(i>=random.length){ i=0 } showimg.textContent= "img/img" + calcNewImg + ".jpg" }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <div id="showimg">###</div> <br> <button id="button">generate</button> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM