samedi 31 octobre 2015

How to select randomly multiple items, with replacement, from an array in javascript

I have an array with all letters of the alphabet plus full stop and space. What I want to do is select randomly a large number of these letters (it does not matter if the same letter gets selected more than once) and print them on the screen. What I've got this far is this:

var letters = ["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", ".", " "];

for (var i = 0; i <= 10; i++) {
    var random_letter = Math.floor(Math.random() * 28);
    var result = [];
    result[i] = [letters[random_letter]];
    document.write(result);
}   

However, when I run the script in Firefox I get this output:

X,C,,N,,,A,,,,T,,,,,.,,,,,,N,,,,,,,T,,,,,,,,G,,,,,,,,,O,,,,,,,,,,G 

Which correctly contains 10 letters and a space. But it also contains all these commas! Which are not part of my array. Why is this thing happening? Am I doing something wrong? Any help would be much appreciated. Alex




Aucun commentaire:

Enregistrer un commentaire