繁体   English   中英

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

[英]Check if one element in array is being used, if so, use another element

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

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

示例:我输入:ABBY我期望它输出:

10跳插孔

15仰卧起坐

10个紧缩

20仰卧起坐

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

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

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

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

我很想知道你的想法。

您需要在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> 

暂无
暂无

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

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