Reputation: 75
I have the following javascript code:
nback.lightElement = function(index) {
var letterArray = new Array('Lorem', 'Ipsum' , 'Dolor', 'Est');
var r = Math.floor(Math.random()*4);
var letter = letterArray[r];
nback.numbers[index] = letter;
nback.numbers.innerHTML = letter;
nback.litCell = letter;
nback.current = letter;
nback.previous.push(nback.current);
};
nback.startGame = function() {
nback.round += 1;
nback.updateRound();
nback.blink_count = 0;
// Make a new game
nback.queue = new Queue();
for (i = 0; i < BLINKS; i++) {
// Populate with random data, less fun than created games
// but this is way easier to program.
nback.queue.queue(Math.floor(Math.random() * 1));
}
// Run the game loop every TIME_BETWEEN_ROUNDS
nback.intervalId = window.setInterval(nback.next, TIME_BETWEEN_BLINKS);
};
This gives my a random word output from the letterArray
for TIME_BETWEEN_BLINKS
milliseconds (e.g. 1000). That word is shown for 1000ms, disappears, and another word appears randomly. This loops BLINKS
-times.
Now I do not want it to choose random words from the letterArray
(the var r = Math.floor(Math.random()*4);
is one of my main concerns). It should just show them one after another. I tried so many different approches (mainly loops of every kind) but still can't make it work. Most of the time I tried loops I got "undefined" (instead of the actual words) or just nothing (blank).
I use https://github.com/chuckha/N-back as a reference.
Help will be much appreciated.
Upvotes: 0
Views: 65
Reputation: 27823
You can use an index for that array that is initialized outside of the function. Here is some code that gives the next word from the array whenever the lightElement function gets called. It also wraps around.
var letterArrayIndex=0;
nback.lightElement = function(index) {
var letterArray = new Array('Lorem', 'Ipsum' , 'Dolor', 'Est');
var letter = letterArray[letterArrayIndex];
letterArrayIndex = (letterArrayIndex+1) % letterArray.length;
nback.numbers[index] = letter;
nback.numbers.innerHTML = letter;
nback.litCell = letter;
nback.current = letter;
nback.previous.push(nback.current);
};
Upvotes: 1