-1

Ive written this function which shows a random item from the array, and then tried to add a bit where it won't pick the same thing twice but now the text doesnt even show.

EDIT Thanks Pointy and Jonas W for spotting that. Working now

var lyrics = function(){
var olditem = document.getElementById("space").innerHTML
var item = space[Math.floor(Math.random() * space.length)];
while (olditem === item) {
    item = space[Math.floor(Math.random() * space.length)];
}
if (olditem !== item) {
    document.getElementById("space").innerHTML = item;      
}};
ThomasStringer
  • 121
  • 1
  • 8

4 Answers4

1

Why dont you do this

function lyrics(){
 var item = Math.floor(Math.random() * space.length);
 document.getElementById("space").innerHTML=space.splice(item,1)[0];
 }

That removes the item from the array, so it cant be used again...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

When it exits the while loop, there is an implied else already there. So I believe your else is causing it not to print. If you just remove that, it should be fine.

    var lyrics = function(){
        var olditem = document.getElementById("space").innerHTML
        var item = space[Math.floor(Math.random() * space.length)];
        while (olditem === item) {
            var item = space[Math.floor(Math.random() * space.length)];
        }
        document.getElementById("space").innerHTML = item;
    };
Kevin Davis
  • 16
  • 1
  • 1
0
var lyrics = function() {
    var olditem = document.getElementById("space").innerHTML;

    var item = space[Math.floor(Math.random() * space.length)];


    while (olditem === item) {
        item = space[Math.floor(Math.random() * space.length)];
    }

    document.getElementById("space").innerHTML = item;
};
Web_Designer
  • 72,308
  • 93
  • 206
  • 262
Mitesh Pant
  • 524
  • 2
  • 15
0

You can shuffle the array, then take items by order.
Shuffle function taken from here: How can I shuffle an array?

var data = [
  'one',
  'two', 
  'three',
  'four',
  'five'
]

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

var pos = 0;
shuffle(data);

var lyrics = function(){
    pos++;
    if (pos == data.length) {
      pos = 0;
      shuffle(data);
    }
    return data[pos];
}


console.log(lyrics());
console.log(lyrics());
console.log(lyrics());
Community
  • 1
  • 1
Giladd
  • 1,351
  • 8
  • 9