简体   繁体   English

如何在JS中不同时遍历数组中的每个对象?

[英]How to iterate over each object in array one by one not simultaneously in JS?

What i want to achieve: A function that iterates over an array and calls other functions one by one, waits until function is complete before calling another 我要实现的功能:遍历数组并一个接一个地调用其他函数的函数,等到函数完成后再调用另一个函数

Every time the function is called it should go back to the start of the array eg 1, 2, 3, 4 if 5 is added, it should call functions that start from 1 before reaching 5 每次调用该函数时它应该回到该阵列例如开始1, 2, 3, 4 ,如果5加入,它应该调用,从开始的函数1到达前5

Here is what i have tried after some searching: 这是我经过一些搜索后尝试过的:

function startFlash(num, value) {
console.log(num);
if (0 < num.length) {
    console.log('settimeup');
    setTimeout(function () {
        sequence.forEach(function (entry) {
            setTimeout(function () {
                if (entry == "red") {
                    flashRed();
                } else if (entry == "green") {
                    flashGreen();
                } else if (entry == "blue") {
                    flashBlue();
                } else if (entry == "yellow") {
                    flashYellow();
                }
            }, 1000)
        })
        num++;
        startFlash(num, value);
    }, 1000);
}

}

So startFlash is being called by a function which uses math.floor to generate a number between 1-4 and depending on the number, adds the color, red/blue/yellow/green to the array sequence 因此startFlash被一个函数调用,该函数使用math.floor生成一个介于1-4之间的数字,并根据该数字向数组sequence添加颜色(红色/蓝色/黄色/绿色)

Now the code above calls all method at the same time which is not what i want. 现在上面的代码同时调用所有方法,这不是我想要的。

Heres something else i've tried after doing more searches: 在进行更多搜索后,我尝试了以下其他方法:

if (sequence[sequence.length -1] == "red") {
            flashRed();
         } else if (sequence[sequence.length -1] == "green") {
            flashGreen();           
         } else if (sequence[sequence.length -1] == "blue") {
            flashBlue();
         } else if (sequence[sequence.length -1] == "yellow") {
            flashYellow();          
         }

Now this code above only calls the latest value in the array like it suggests, but i need it to start from the first value in the array 现在上面的代码只像建议的那样调用数组中的最新值,但是我需要它从数组中的第一个值开始

Any help? 有什么帮助吗?

Consider using Promises 考虑使用Promises

let chain = Promise.resolve();
sequence.forEach(entry=>{
    chain = chain.then(()=>{
        if (entry == "red") flashRed()
        // ... etc
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM