English 中文(简体)
接下来是阵列,无休止地循环
原标题:JS return next in array, cycle endlessly

我有这样一份名单;

var mystrings = [
     apple ,
     banana ,
     orange 
]

I would like a function I can call at anytime to get the next string. And when the end of the list is reached, start over and get the first one again.

我将这份清单用于必须按名单顺序排列的科安科课程清单,但是,如果需要的话,我不会坐在名单上。

I can t figure it out and it is somehow hard to google. Any ideas?

最佳回答

这里的职能很少:

function enumerator(array) {
    var index = 0;
    return function () {
        return array[index++%array.length]
    }

}

呼吁:

var next = enumerator(["a", "b"]);
next(); // a
next(); // b
next(); // a
问题回答
// Your array is declared in global scope
var mystrings = [
     apple ,
     banana ,
     orange 
];

// A global index variable...
var strIndex = 0;
function getNextString() {
   // If you reached the end of the array, reset to 0
   if (strIndex === mystrings.length - 1) {
       strIndex = 0;
       return mystrings[strIndex];
   }
   // Otherwise, increment it and return the new value
   else return mystrings[++strIndex];
}

// Call it as
var currentString = getNextString();

采用外部指数变量和增减,或将其重新编为每打1美元





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签