检查是否正在使用数组中的一个元素,如果使用,则使用另一个元素

时间:2018-10-31 18:38:16

标签: javascript arrays random switch-statement

如何检查是否正在使用一个元素,以及是否要在Switch Case语句中使用另一个元素。

@snapshot = {
    captable: @captable,
    evet: @event, 
    shareholders: @shareholders
}
//Input
function myFunction() {
  
var myArray = ["60","50", "20", "30", "15", "10"];
  var randomJumpingJacks = myArray[Math.floor(Math.random()*myArray.length)];
  var randomCrunches = myArray[Math.floor(Math.random()*myArray.length)];
   
    var workOut = document.getElementById("myInput").value;
  
  
var text = "";
for(const char of workOut.toUpperCase()){
    switch(char) {
        case "A":
        case "I":
        case "N":
        case "X":
            text += randomJumpingJacks;
            text += " Jumping Jacks";
                  
        break;
        case "B":
        case "J":
        case "Q":
        case "Y":
            text += randomCrunches;
            text += " Crunches";       
          break;
          case " ":
            /*text += " break ";*/
        break;
       
        default:
        text += "I have never heard of that fruit...";    
    }
  text +=" "
  text +="<br>"
}
  
    document.getElementById("excercise").innerHTML = text;
}

示例: 我输入了:ABBY 我希望它能输出:

10个跳插孔

15个仰卧起坐

10个仰卧起坐

20个仰卧起坐

我不确定我是否使用正确的术语,但是我将案例A,I,N,X称为“跳跃块”,将案例B,J,Q,Y称为“紧缩块”。

如果调用的字符来自同一块,则倾向于显示相同的随机数。

在Crunches块的第二个字符(B)上,它自然输出15,但是由于它被用于第一个字符(也为B),我希望它使用其他元素,

,第三个字符(Y)也在Crunches块上,我希望它使用与前两个元素不同的其他元素,依此类推,并重复4次。

我很想知道你的想法。

1 个答案:

答案 0 :(得分:0)

您需要将随机逻辑移至for循环内。要获得字符串中每个字母的新随机数,您需要在每次循环执行时重新分配该值。请参见下面的代码。

function myFunction() {
  
var myArray = ["60","50", "20", "30", "15", "10"];

   
    var workOut = document.getElementById("myInput").value;
  
  
var text = "";
for(const char of workOut.toUpperCase()){
  var randomJumpingJacks = myArray[Math.floor(Math.random()*myArray.length)];
  var randomCrunches = myArray[Math.floor(Math.random()*myArray.length)];

    switch(char) {
        case "A":
        case "I":
        case "N":
        case "X":
            text += randomJumpingJacks;
            text += " Jumping Jacks";
                  
        break;
        case "B":
        case "J":
        case "Q":
        case "Y":
            text += randomCrunches;
            text += " Crunches";       
          break;
          case " ":
            /*text += " break ";*/
        break;
       
        default:
        text += "I have never heard of that fruit...";    
    }
  text +=" "
  text +="<br>"
}
  
    document.getElementById("excercise").innerHTML = text;
}
<!DOCTYPE html>
<html>
<body>

<p>Input some characters  and click the button.</p>
<p>Your excericse routine will display based on your input.</p>

<input id="myInput" type="text">

<button onclick="myFunction()">Try it</button>
<p>
  <span id="reps"></span>
  <span id="excercise"></span>
  </p>

</body>
</html>