jeudi 26 octobre 2017

JavaScript random item from an imported array behaving strangely

The following code seems to be behaving strangely. Basically, I'm importing a list of line-separated sentences from a text file, then making an array out of them. But when I try to choose a random sentence from the array, it doesn't work because sentenceString becomes undefined.

However, when I run Math.floor(Math.random() * (sentenceArr.length) + 1); I get a nice random number as expected.

And when I run sentenceArr.length I get the number 12, which is indeed the length.

What am I missing?

    var sentenceArr = [];

    $.get('sentences.txt', function(data){
        sentenceArr = data.split('\n');
    });

    var rand = Math.floor(Math.random() * (sentenceArr.length) + 1);

    var sentenceString = sentenceArr[rand];

    var sentence = sentenceString.split(' ');




Aucun commentaire:

Enregistrer un commentaire