0

I have build an array loader with javascript.

Here the jsfiddle

When I directly click last, I get undefined. I tryed to catch it up with something like this

var lastWord = (function() {

            return function() {
            var resultWord = wordArray[--count % wordArray.length];
                if (typeof resultWord == "undefined")
                { 
                return false;
                }
                else 
                {
                return wordArray[--count % wordArray.length];
                }
            }
        }

}());

But didn't worked, any suggestions?

Johnny000
  • 2,058
  • 5
  • 30
  • 59

2 Answers2

0

The reason it is undefined for the first time is because there is nothing in wordArray at negative indeces. There is no "last" word before you have hit update. Does that make sense? It works fine after you have hit update once.

thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
0

Try http://jsfiddle.net/ayQH2/2/

The problem is that the sign returned by the modulus operator is the sign of its first operand. So, for example

(-17) % 12 // == -5 , not 7

This will probably work, and does not include the extra function wrappers:

var nextWord = function() {
    // silly work-around for negative modulus issue
    var index = (++count % wordArray.length) + wordArray.length
    return wordArray[index % wordArray.length];
};
var lastWord = function() {
    // silly work-around for negative modulus issue
    var index = (--count % wordArray.length) + wordArray.length
    return wordArray[index % wordArray.length];
};

There are plenty of other ways to deal with this. Perhaps a better one would be to ensure that count never escapes the proper range, doing something like

count = (count == wordArray.length - 1) ? 0 : count++; // increment
count = (count == 0) ? wordArray.length - 1 : count--; // decrement
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103