每秒记录一个嵌套循环元素至少一分钟?在Javascript中


let innerArrayOne = [1,"red","fed"]
let innerArrayTwo = [2,"blue","you"]
let innerArrayThree = [3,"green","bean"]
let innerArrayFour = [4,"yellow","fellow"]
let arrayS = [innerArrayOne,innerArrayTwo,innerArrayThree, innerArrayFour]

以下是我迄今为止尝试过的

for(let i = 0; i < arrayOfDoom.length; i++){
console.log("----")
console.log(arrayOfDoom[i])
console.log("----")
for(let j = 0; j < arrayOfDoom[i].length;j++)
console.log(arrayOfDoom[i][j])
}
}

这是我做的测试数据。以下是我迄今为止所做的尝试。这为您提供了数组中的每个元素。


function loop(count, callback, done) {
let counterForLoop = 0;


let next = function () {setTimeout(iteration, 500);};

let iteration = function () {
if (counterForLoop < count) { callback(counterForLoop, next);
} else { done && done();}

counterForLoop++; 
}
iteration();
}
loop(10000, function (i, next) {next();})

loop(9, function (i, nextI) {
console.log("----")
console.log(i)
console.log("----")
loop(3, function (j, nextJ) {
console.log(arrayS[i][j]);nextJ();
}, nextI);});

这是我检查的唯一一个关闭StackOverflow。它起作用,但在第一个数组中的最后一个元素之后结束。我不完全理解递归,所以每次我尝试编辑时,比如在计数器达到8后将其设置为零,它就会破坏它

1 
red 
fed
2
blue
you
....

有一个元素出现,每秒一到两分钟,循环一旦结束,只需要重复。

有什么想法或我应该研究什么?

对于所有未来的人来说,这就是我让工作的方式

function getRandomInt(max) {
return Math.floor(Math.random() * max);
}

let i = 0;
let loopCounter = 0;
let randomNumber = 1
const outerLoop = () => {
for (i; i < arrayS.length;){
console.log(randomNumber);
console.log(arrayS[randomNumber][loopCounter])
i++;
loopCounter++;
if(loopCounter === 3){
loopCounter = 0
randomNumber = getRandomInt(8)

}
if(i === 4){
i = 0
}
break;
}
}
setInterval(outerLoop, 2000);

未来的人还应该考虑将问题一分为二:(1(在固定时间内按间隔做任何事情,以及(2(随机记录。

setInterval可以提供的一点打扮可以隐藏时间数学,并在指定的经过时间后停止。

随机记录也可以通过混洗,然后按顺序记录来改进,以获得随机性而不重复。

let innerArrayOne = [1,"red","fed"];
let innerArrayTwo = [2,"blue","you"];
let innerArrayThree = [3,"green","bean"];
let innerArrayFour = [4,"yellow","fellow"];
let arrayS = [innerArrayOne,innerArrayTwo,innerArrayThree, innerArrayFour];
// fisher-yates shuffle, thanks to https://stackoverflow.com/a/2450976/294949
function shuffle(array) {
let currentIndex = array.length,  randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// invoke fn on a set interval until elapsed ms have elapsed
function repeat(fn, interval, elapsed) {
fn() // up to author if we start right away
const start = (new Date()).getTime(); // ms since epoch
const id = setInterval(() => {
const now = (new Date()).getTime();
if (now - start > elapsed) {
clearInterval(id);
} else {
fn()
}
}, interval);
}
let shuffledArray = shuffle(arrayS.slice());
let index = 0;
repeat(() => {
console.log(shuffledArray[index])
if (index < shuffledArray.length-1) index++;
else {
shuffledArray = shuffle(arrayS.slice());
index = 0;
}
}, 800, 4800)

最新更新