简体   繁体   English

我如何在javascript中实现这个功能

[英]How i can make this function in javascript

i am in a bootcamp and i got stuck here, i tried to do it by myself and it didn't worked, then i copy and paste the code that the mentor wrote, and is not working also for some reason, i should get a random color into the gamePattern variable.. any ideas ?我在训练营中,我被困在这里,我试图自己做,但没有成功,然后我复制并粘贴导师编写的代码,并且由于某种原因也无法正常工作,我应该得到一个随机颜色进入gamePattern变量..有什么想法吗? Thank you.谢谢你。

var buttonColours = ["red", "blue", "green", "yellow"];

var gamePattern = [];

function nextSequence() {

  var randomNumber = Math.floor(Math.random() * 4);
  var randomChosenColour = buttonColours[randomNumber];
  gamePattern.push(randomChosenColour);

First of all, in your code nextSequence is missing a closing bracket } and you would need call the function nextSequence() at the end to actually execute your logic.首先,在您的代码中nextSequence缺少右括号} ,您需要在最后调用函数nextSequence()才能实际执行您的逻辑。

However, I'd recommend to avoid functions that change values of the global scope because this easily becomes a pitfall for untraceable errors and application behavior.但是,我建议避免使用更改全局范围值的函数,因为这很容易成为无法追踪的错误和应用程序行为的陷阱。 Therefore, I'd recommend to have this helper function randomChoiceFromList that gives you a random item from a list.因此,我建议使用此辅助函数randomChoiceFromList为您提供列表中的随机项目。 Furthermore, as it is more abstract it is potentially reusable.此外,由于它更抽象,因此它具有潜在的可重用性。

 var buttonColours = ["red", "blue", "green", "yellow"]; var gamePattern = []; function randomChoiceFromList(list) { const randomNumber = Math.floor(Math.random() * (list.length)); return list[randomNumber]; }; gamePattern.push(randomChoiceFromList(buttonColours)); console.log(gamePattern);

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

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