1

Sometimes the randomly-generated letter equals to 'undefined'

Anyone know why?

Code:

<script type="text/javascript"> 
var myArray= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

randomnumber=Math.floor(Math.random()*27);
alert(myArray[randomnumber]);
5
  • Looks like it's working perfect here in this jsfiddle Commented Aug 27, 2011 at 5:58
  • @macek, did you try loading it more than once? It most assuredly pops blanks too. Commented Aug 27, 2011 at 6:14
  • yeah I can't replicate it either in that jsfiddle Commented Aug 27, 2011 at 6:17
  • 1
    keep clicking. 1/13 will fail Commented Aug 27, 2011 at 6:23
  • sorry I should have been clearer, I meant "keep" reloading. See my answer and comment for full explanation. Commented Aug 27, 2011 at 16:37

1 Answer 1

3

Well, it could have something to do with your Math.floor(Math.random()*27) using the number 27 when there are 26 letters in the English alphabet.

math random returns 0-.999... 
math random * 27 returns 0-26.999...
floor math random * 27 returns 0 - 26 
an array with every english letter has 26 items 
which means it has items indexed from 0-25

so you get a blank in each box 1/27 of all loads. However, once "#next" has been seeded it will always stay a "letter" because you're replacing it with

$("#next").text(good[randomnumber]);

When randomnumber=27 good[randomnumber]=undefined and $("#next").text(undefined) does nothing so the contents of "#next" remain unchanged. Still broken, less obvious. Just change 27 to 26 and you're done.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, there is a petition for a new letter in the English language making a total of 27. Perhaps ogps92 is just ahead of the new standard. Some day your answer will be wrong and we will vote it down. :o)
That solves the problem I guess... But Why it only happens at the beginning when the is loaded (and not when the other random letters are generated)
Because when you already have contents in the square passing "undefined" to text() does nothing. Try watching the output with something like jsfiddle.net/zGghJ/2 and eventually you'll see 27:undefined and notice that the letter in the final box just stays the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.