'How to change a string to a URL and import it as an image?

I am thinking of something like this:

let img_1 = "./img/image.png";
let player = 1;
document.getElementById("player_img").src = "img_" + player;

then it can display ./img/image.png on the webpage

but the code above does not work, what is the right code?



Solution 1:[1]

Probably the best approach is use an array.

Like this

let img_ = ["./img/image.png","./img/image.png","./img/image.png"];
let player = 1;
document.getElementById("player_img").src = img_[player - 1];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1