mercredi 22 août 2018

Randomly Selecting Values From Array Without Repeating

Hi: I am new to Javascript and HTML, been studying on my own for a month. I am doing a small project where when I click a button, 3 random workout exercises appear in a table. I will attach my code to show what I have so far.


Issue: When the for loop runs, it prints the same randomly selected item 3 times, not 3 different items.


Goal: When I click a button, the array prints 3 different array values.

var workouts = ['situps', 'planks', 'hollow rock']
var copy = workouts.slice();

var table = '';
var i = 1;

for(var j = 0; j < i; j++)
{
    var answer = copy.splice(Math.floor(Math.random()*workouts.length), 1); 
    table += '<tr>';
    table += '<td>';
    for(var i = 0; i < 1; i++){
        table += answer;
    }
    table += '</td>';
    table += '</tr>';
}

function potato() {
document.getElementById('hi').innerHTML += ('<table border = 1>' + table + '</table>');
}

//Output: Sit ups, Sit ups, Sit ups




Aucun commentaire:

Enregistrer un commentaire