gpt4 book ai didi

Javascript:元素没有从数组中删除

转载 作者:行者123 更新时间:2023-12-03 01:58:17 25 4
gpt4 key购买 nike

我正在尝试制作一个 4x4 的方 block 网格,每 1/4 秒随机改变一次颜色。如果网格改变颜色,它有 2 秒的冷却时间才能再次改变。我试图通过从数组中删除该元素来实现此目的,然后当发生 8 个以上更改时,它会被添加回来。我的问题是,元素似乎并没有真正从数组中删除,我不确定为什么。

你可以在这里看到我的代码

http://jsfiddle.net/jb60r6dx/1/

var eligable = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
var deleted;
var count = 0;


function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

setInterval(function() {
//re-add the element
//8 cycles == 2 seconds
if (count % 8 == 0 && count != 0) {
eligable.push(deleted.shift());
}

//find random element
var rand = Math.floor(Math.random() * eligable.length);
var element = document.getElementById(eligable[rand]);

//get random color
var r = getRandomInt(0, 255);
var g = getRandomInt(0, 255);
var b = getRandomInt(0, 255);

//change color
element.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")";
document.getElementById("colorvalue").innerHTML = r + " " + g + " " + b;

//remove changed grid
removeEle(eligable[rand]);

//count cycle
count += 1;
}, 250);

//Removes the selected element and push to deleted array
function removeEle(ele) {
deleted.push(ele);
var index = eligable.indexOf(ele);
if (index > -1) {
eligable.splice(index, 1);
}
}

最佳答案

我已将js代码更改为以下内容。试试这个,它的工作原理

var eligable = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
var deleted=[];
var count = 0;

function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

setInterval(function() {
//re-add the element
//8 cycles == 2 seconds
if (count % 8 == 0 && count != 0) {
eligable.push(deleted.shift());
}

//find random element
var rand = Math.floor(Math.random() * eligable.length);
var element = document.getElementById(eligable[rand]);
if(element){

}
if(element){
//get random color
var r = getRandomInt(0, 255);
var g = getRandomInt(0, 255);
var b = getRandomInt(0, 255);

//change color
element.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")";
}
var colorVal = document.getElementById("colorvalue")
if(colorVal)
colorVal.innerHTML = r + " " + g + " " + b;

//remove changed grid
removeEle(eligable[rand]);
console.log(eligable);
//count cycle
count += 1;
}, 250);

//Removes the selected element and push to deleted array
function removeEle(ele) {
deleted.push(ele);
var index = eligable.indexOf(ele);
if (index > -1) {
eligable.splice(index, 1);
}
}

关于Javascript:元素没有从数组中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com