简体   繁体   中英

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.

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

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

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

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> 

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