samedi 24 septembre 2016

Filling An Array With random Integer Values

I bought a JavaScript book and am working my way through. I've reached a part of the book that doesn't make sense. I'm hoping you guys and girls will be able to clarify as the book doesn't.

Please see the code below that generates 6 random numbers and renders them to a div with id=panel.

function init(){
var panel = document.getElementById('panel');
var i, rand, temp, str, num = [];

for (i = 1; i < 50; i ++){
    num[i] = i;
}

for (i = 1; i < 50; i ++){
    rand = Math.ceil(Math.random()*49);
    temp = num[i];
    num[i] = num[rand];
    num[rand] = temp;
}

str = 'Your six lucky numbers:<br>';
for (i = 1; i < 7; i ++){
    str += num[i];
    if (i !==6){str += ' - ';}
}
panel.innerHTML += str;

}
document.addEventListener('DOMContentLoaded', init, false);

The book says that the second loop (that initilizes the random variable) contains a sort algorithm that ensures no two elements contain the same number.

I'm not sure how this is possible, I don't see any code in there that stops rand containing a duplicate number and consequently having that value stored in num. The book doesn't really provide much of an explanation of what is going on.

Could someone please let me know how, if at all, loop two is preventing 'num` from containing the same number?

Thanks all

P.S. Sorry if this question doesn't adhere to Stack Overflow guidelines. I don't come on here often, only when I get really stuck and can't find an answer elsewhere.




Aucun commentaire:

Enregistrer un commentaire