简体   繁体   中英

Write a function “giveMeRandom” which accepts a number n and returns an array containing n random numbers between 0 and 10

I need to Write a function "giveMeRandom" which accepts a number n and returns an array containing n random numbers between 0 and 10

I can't push generate array of n (arg) length. It generates only one.

const giveMeRandom = function(n) {
    let arrWithNums = [];
    for(i = 0; i < n.length; i++) {
        return arrWithNums.push(Math.floor(Math.random() * 10)); 
    }
    return arrWithNums;
}
console.log(giveMeRandom(4));

n is a number which does not have a length. Just use following for loop:

for (let i = 0; i < n; i++) {...}

Also remove the return statement inside of the loop.

The first problem is n.length . The number 4 has a length of one, and if i < 1 then the loop will not run at all. You just want n in this place instead.

The other problem is that you're returning a value at every repetition of the loop, which stops the function running. Only return a value once at the end to fix this problem.

Here's the full code:

 function giveMeRandom(n) { let arrWithNums = []; for(i = 0; i < n; i++) { arrWithNums.push(Math.floor(Math.random() * 10)); } return arrWithNums; } console.log(giveMeRandom(4));

 const giveMeRandom = function(n) { let arrWithNums = []; for (i = 0; i < n; i++) { arrWithNums.push(Math.floor(Math.random() * 10)); } return arrWithNums; } console.log(giveMeRandom(6));

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