繁体   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