The first problem here is that Math.floor((Math.random() * 3) + 1)
will return a number between 1 to 3. Your array only has elements at index 0, 1, and 2. So abc
won't be printed at all.
The second problem is, there is no guarantee that your calculation will return every single number 0, 1 and 2 exactly once. You could be getting arr[1]
three times in a row, resulting in pqr
being printed 3 times.
I initially voted to mark this question as a duplicate of How to randomize (shuffle) a JavaScript array?. My thought was that you can simply shuffle the array, then print the shuffled array. However, since this question has been reopened, I will propose an alternate solution.
arr = ['abc','pqr','mnc'];
while (arr.length > 0) {
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]);
arr.splice(index, 1);
}
Randomly select one element in the array, print it and then remove it from the array. Repeat until there are no more elements.
` HTML element (as opposed to "ordered list", `
`). I would refer to the shuffled list as "shuffled", or "randomized", not "unordered".
– Amadan Sep 25 '15 at 03:17