jeudi 5 janvier 2017

Browser Freezing on Loop Run (JavaScript)

I am trying to rebuild a paragraph of words randomly without repeating the same word in JavaScript:

var  para = 'dashing through the snow' +
        ' in a one horse open sleigh' +
        ' over the fields we go' +
        ' laughing all the way';
console.log(para);
function getRandomNumber(min, max) 
{
     return Math.floor(Math.random() * (max - min)) + min;
}

var words = para.split(' ');
var newPara = '';

for(var i = 0; i < words.length - 1; i++)
{
  var curWord = words[getRandomNumber(0,words.length - 1)];

  if(newPara.indexOf(curWord) == -1)
  {
    newPara += curWord + ' ';
    console.log(newPara);
  } else
  {
    i--;
  }

}

The code splits a paragraph into an array of words (19 in all). I then use a loop to loop through this array and select a word at random, checking if the word has been added to the newPara string. If it has not, I add it. If it has, I subtract 1 from the loop run. The problem is that the script causes the browser to freeze when I use the else statement to subtract one from the loop. Any help on this problem is appreciated.




Aucun commentaire:

Enregistrer un commentaire