Gabe Perry
Gabe Perry

Reputation: 79

JavaScript Function that creates 4 random numbers that push to an array?

Instead of doing this:

var crystalValues = [];
crystalValues[0] = Math.floor(Math.random()*12+1),
crystalValues[1] = Math.floor(Math.random()*12+1),
crystalValues[2] = Math.floor(Math.random()*12+1),
crystalValues[3] = Math.floor(Math.random()*12+1),  

How can I create a function that returns 4 random numbers?

Upvotes: 1

Views: 219

Answers (4)

Ryan Nourbaran
Ryan Nourbaran

Reputation: 5

A for loop would do the trick if you're trying to save time typing the function out.

random4() {
    var crystalValues = [];
    for (var i=0; i < 4 ; i++) {
        randomNumber = Math.floor(Math.random()*12+1);
        while (crystalValues.indexOf(randomNumber) !== -1) {
            randomNumber = Math.floor(Math.random()*12+1);
        }
        crystalValues[i] = randomNumber;
    }
    return crystalValues;
}

Upvotes: 0

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

Use a for loop.

Try this:

var crystalValues = [];

for(var i = 0;i < 4;i++){
  crystalValues.push(Math.floor(Math.random()*12+1))
}

console.log(crystalValues);

Upvotes: 0

Blindman67
Blindman67

Reputation: 54059

The function below creates an array of random ints.

The count sets how many, min and max set the min and max random values

    function createRandomArray(count,min,max){
        const rand = () =>  Math.floor( Math.random() * (max - min) + min);
        const vals = [];
        while(count-- > 0){ vals.push(rand()) }
        return vals;
    }
    console.log(createRandomArray(4,1,13));
    
    

You can assign them to another array as follows

const crystalValues = [];
crystalValues.push(...createRandomArray(4,1,13))

Or just directly assign them

const crystalValues = createRandomArray(4,1,13);

Upvotes: 1

Shalitha Suranga
Shalitha Suranga

Reputation: 1146

You can simply use Array.from()

var gen = () => {
	return Array.from({length: 4}, () => Math.floor( Math.floor(Math.random()*12+1)));
}

console.log(gen());

Upvotes: 0

Related Questions