Sean Poh
Sean Poh

Reputation: 93

How to get a random value from an array?

This is a bit different from the other questions here. I've looked at the other questions and I still can't solve the problem. The difference is explained in the paragraph below.

Firstly, here's the code.

        var colors = ['#ffff00', '#FF009C'];
        var random_color = colors[Math.floor(Math.random() * colors.length)];
        for (var i = 0; i < document.querySelectorAll('#menu a').length; i++) {
        document.querySelectorAll('#menu a')[i].style.color = random_color;}
<div id="menu">
        <h1><a>Project 1<a></h1>
        <h1><a>Project 2</a></h1>
        <h1><a>Project 3</a></h1>
        <h1><a>Project 4</a></h1>
        </div>

What I am trying to do is to select one of the values in the array as the colour for '#menu a'. I don't want a value in between the values I wrote or anything. Just either #ffff00 or #ff009c or any value that I put in the array.

edit: Thanks everyone! I just realised that my code is working. Sorry for making you all solve my problem when it wasn't a problem. My bad.

Upvotes: 0

Views: 84

Answers (4)

Arkej
Arkej

Reputation: 2241

Change your line:

var random_color = colors[Math.floor(Math.random() * colors.length)];

into a function:

random_color = function() { return colors[Math.floor(Math.random() * colors.length)]; }

This way it will be executed for every anchor in your menu

    var colors = ['#ffff00', '#FF009C'];
    
    random_color = function() {
    	return colors[Math.floor(Math.random() * colors.length)];
    }
    
    for (var i = 0; i < document.querySelectorAll('#menu a').length; i++) {
    document.querySelectorAll('#menu a')[i].style.color = random_color();}
    <div id="menu">
    <h1><a>Project 1</a></h1>
    <h1><a>Project 2</a></h1>
    <h1><a>Project 3</a></h1>
    <h1><a>Project 4</a></h1>
    </div>

Upvotes: 1

Tal
Tal

Reputation: 141

Use: var color = colors[Math.floor(Math.random() * (colors.length - 1))]

Upvotes: 1

Yogesh Mistry
Yogesh Mistry

Reputation: 2152

Your code is almost correct. You just need to move your random code generator code inside your loop.

var colors = ['#ffff00', '#FF009C'];

for (var i = 0; i < document.querySelectorAll('#menu a').length; i++) {
    var random_color = colors[Math.floor(Math.random() * colors.length)];
    document.querySelectorAll('#menu a')[i].style.color = random_color;
}

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68433

Check this solution on how to get random number between two values

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Now just replace min and max with 0 and length of array

var random_color = colors[getRandomInt(0, colors.length-1)];

Upvotes: 1

Related Questions