简体   繁体   中英

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?

try this:

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

 }

as @Steve Medley said the result expected to be string. so if recommendedProducts contains some string you should add this string in each iteration of loop to your result and return it after your loop has finished( also this is what i have understood from question)

Try this:

function randomProduct(num) {
    var iter = num;
    var randomArray = [];
    for (var i = 0; i < iter; i++) {
     randomArray.push(recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)]);
    }
    return randomArray.join(); // returns it as a string
}

First you need to append the items to an array using push

Second you need to return outside of the loop, if you retrun from the inside of the loop you break the function after the first iteration.

The return rand take you off the function at the first result.

You can remove the loop, just return the rand, and call the function 4 times.

If you want the function to return array of random numbers, instead of return rand , push the results to new array and return the array when the for loop is done.

在循环中,变量rand的值将等于上次迭代输出的值,您需要返回对象数组而不是单个对象以获得所需的结果。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM