I tried to write some javascript that takes the entries of an array and shuffles the order. It’s not compiling like it should though. Seems to only run through the for loop once. What am I missing?
//random number between 1 and num
function randInt(num){
return Math.floor(num*Math.random()+1);
}
//shuffles deck (array) of any size
function shuffle(array){
var newArray = new Array();
var n = array.length;
for(i=0; i<n; i++){
var entry = randInt(array.length) - 1;
newArray[i] = array[entry]; //assigns random entry in initial array to new array
array = array.splice(entry, 1); //removes the entry that was stored into newArray
}
array = newArray;
}
array.splicemodifiesarrayand returns the removed item(s). You want to discard the element, so just do this instead of overwritingarray:+ 1inrandIntand doing- 1afterwards seems superflouous.var i = 0(though look at my last point).[]instead ofnew Array()since the latter is not generally used.array:arrayso you cannot loop up tonanymore as the length becomes 1 less each time. You may wantwhile(array.length > 0) { ... }instead of theforloop.