简体   繁体   English

Javascript:如何每秒循环遍历每个数组的项目

[英]Javascript: How to loop through every array's item every second

Lets say i have an array like this:可以说我有一个这样的数组:

var arr = [0,1,2,3,4];

so i want to make a for loop that loops through the array and console logs every item, but i want it to console log separately every item and each item will be console logged a second after the previous item, how can i do this?所以我想制作一个循环遍历数组和控制台记录每个项目的for循环,但我希望它单独记录每个项目,并且每个项目将在前一个项目之后的第二个控制台记录,我该怎么做?

You can use an interval. 您可以使用间隔。 Here is an example: 这是一个例子:

 var arr = [0,1,2,3,4]; var index = 0; setInterval(function(){ console.log(arr[index++ % arr.length]); }, 1000) 

The example above will loop through the array more then once. 上面的示例将遍历数组,然后执行一次以上。 If you want to loop the array only once, you can stop the interval when all the elements were logged. 如果只想循环一次数组,则可以停止记录所有元素的时间间隔。

 var arr = [0,1,2,3,4]; var index = 0; var interval = setInterval(function(){ console.log(arr[index++]); if(index == arr.length){ clearInterval(interval); } }, 1000) 

Just thought I'd clean up @mhodges answer a little bit, with a cleaner ES6 generator function : 只是以为我会用更清洁的ES6生成器功能来清理@mhodges答案

 let myArray = [0, 1, 2, 3, 4] let interval = setInterval(gen => { const { value, done } = gen.next() if (done) { clearInterval(interval) } else { console.log(value) } }, 1000, myArray[Symbol.iterator]()) 

Just for the sake of it, here is an example using an ES6 generator function to iterate over an array's contents. 仅出于此目的,这是一个使用ES6生成器函数迭代数组内容的示例。 You would continue to call generator.next() inside a setInterval() until you are done iterating over the entire array, in which case, you clear the interval and you're done. 您将继续在setInterval()调用generator.next(),直到完成对整个数组的迭代为止,在这种情况下,请清除间隔并完成操作。

 var myArr = [0,1,2,3,4]; function* iterateOverArray (arr) { var i = 0; while (i < arr.length) { yield arr[i++]; } } var generator = iterateOverArray(myArr); var interval = setInterval(function () { var nxt = generator.next(); if (!nxt || nxt.done) { clearTimeout(interval); } else { console.log(nxt.value); } }, 1000); 

I wanted to do this as well, this is what I tried in my code:我也想这样做,这是我在代码中尝试的:

array=[];数组=[];

setInterval(mediaTweet, 1000 *60 *2)// every 2min setInterval(mediaTweet, 1000 *60 *2)// 每2分钟

function mediaTweet () { function mediaTweet () {

let tweet = { status: array[index++ % array.length] }让 tweet = { status: array[index++ % array.length] }

T.post('statuses/update', tweet, tweeted); T.post('statuses/update', tweet, tweeted); } }

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

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