简体   繁体   English

如何从数组中获取随机值?

[英]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'. 我想做的是选择数组中的值之一作为“ #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. 只是#ffff00或#ff009c或我放入数组中的任何值。

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 现在只需将min和max替换为0数组的长度

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM