samedi 9 juillet 2016

Picking more than one random from an array

I wrote this function:

function randomProduct(num) {
  var iter = num;
  for (var i = 0; i < iter; i++) {
    var rand = recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
    return rand
  }
}

Which is supposed to pull from the recommendedProducts array however many are needed when the function is called. So basically randomProduct(1) would pull 1 and randomProduct(4) would pull 4, etc.

However no matter what number I enter in there when I test is through the console, I always only get 1 array item returned.

console.log(randomProduct(1));
console.log(randomProduct(2));
console.log(randomProduct(3));
console.log(randomProduct(4));

What am I doing wrong?




Aucun commentaire:

Enregistrer un commentaire