【发布时间】:2021-06-11 22:57:14
【问题描述】:
我创建了一个简单的 html 页面,页面中有一个单击按钮。 单击按钮时,主体颜色需要随机更改为我在数组中定义的四种颜色之一。 那是有效的。然而,它有时会两次或更多次生成相同的颜色。所以每次点击都需要给body一个不同的颜色。 我创建了一个空数组并将生成的值添加到该数组中,如果值存在,我希望它生成一个新的随机数。
<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>
这是我的脚本
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.
【问题讨论】:
-
如果所有颜色都被选中了怎么办?还是只是想防止上次选择的颜色再次被选中?
-
是的,确实,防止再次选择最后一种颜色。谢谢。
标签: javascript arrays function