简体   繁体   中英

how to add random items to an array using a function that generates random numbers

I have this problem I'm not really sure how to do it. I'm having trouble figuring out how to add items to an array using a function that generates random numbers.

First I have to build a function that takes three parameters. one is the minimum random number, the other one is the maximum, the third parameter is the length of the array.

I've tried some stuff like removing the variable x setting it to an empty array.

 var newArray = [generateRandomArray(10, 1, 10)] function getRandomInt(min, max) { return Math.floor(Math.random() * ( max + 1 - min)) + min; } var generateRandomArray = function(max, min, length) { var x; for (y = 1; y >= length; y++) { x = [x.push(getRandomInt(min, max))] console.log(x) } return x; }

var newArray = [generateRandomArray(10, 1, 10)] returns [5, 7, 9, 6, 6, 10, 8, 10, 9, 7]

I just get []

You were attempting to call generateRandomArray in the snippet before the function existed, and your for loop in generateRandomArray would never run as y started as 1 and you were comparing it as >= length :

 function getRandomInt(min, max) { return Math.floor(Math.random() * ( max + 1 - min)) + min; } var generateRandomArray = function(max, min, length) { var x = []; for (var y = 0; y < length; y++) { x.push(getRandomInt(min,max)); } return x; } var newArray = generateRandomArray(10, 1, 10); console.log(newArray);

Comments in code to show fixes.

Also just as a side note, I would recommend switching the min and max around on one of the two functions that use them for consistency. Just a Good Practice.

 //moved generateRandomArray function to beginning so it is defined before it is called var generateRandomArray = function(max, min, length) { var x = []; //initialise array for (y = 1; y <= length; y++) { //fix the incorrect sign so the loop works x.push(getRandomInt(min, max)); //fix the fact you kept overriding x and instead just push to the array console.log(x) } return x; } var newArray = [generateRandomArray(10, 1, 10)] console.log("newArray", newArray); function getRandomInt(min, max) { return Math.floor(Math.random() * ( max + 1 - min)) + min; }

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