簡體   English   中英

編寫一個 function “giveMeRandom”,它接受一個數字 n 並返回一個包含 n 個介於 0 和 10 之間的隨機數的數組

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

我需要編寫一個 function “giveMeRandom”,它接受一個數字 n 並返回一個包含 n 個介於 0 和 10 之間的隨機數的數組

我無法推送生成 n (arg) 長度的數組。 它只生成一個。

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 是一個沒有長度的數字。 只需使用以下 for 循環:

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

還要刪除循環內的 return 語句。

第一個問題是n.length 數字4的長度為 1,如果i < 1則循環根本不會運行。 你只想要n在這個地方。

另一個問題是每次循環重復時都會返回一個值,這會停止 function 的運行。 最后只返回一個值來解決這個問題。

這是完整的代碼:

 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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM