I have create a simple html page with a click button in the page. When clicking on the button, the body color needs to change randomly with one of the four colors which I have defined in an Array. That is working. However it sometimes generated the same color twice or more times. So every clicks need to give the body a different color. I have created an empty array and add the generated value in this array and if the values exist, I want it generate a new random number.
<main>
<div class="container">
<h2>Background color: <span class="color">#f1f5f8</span></h2>
<button class="btn btn-hero" id="btn">click me</button>
</div>
</main>
and this my script
const bodyColor = ["red", "#f8fdbb","rgba(0,150,3,0.5)", "yellow"];
//Getting the body
const myBody = document.body;
//getting the myBtn id
const myBtn = document.getElementById('btn');
myBtn.addEventListener('click', myFunc);
let myArray = [];
function myFunc(){
//get a number between 0-3
let randnr = Math.floor(Math.random() * bodyColor.length);
console.log(randnr);
if(myArray.includes(randnr)){
alert("value exist in array");
?
}else{
//creating a bodycolor
const myBodyColor = bodyColor[randnr];
//adding the created bodycolor to the body tag
myBody.style.background = myBodyColor;
myArray.push(randnr);
console.log(myArray);
}
}```
Any suggestion how to fix it?
Thanks,
E.