简体   繁体   English

math.random 总是在数组中返回 1

[英]math.random always returning 1 in array

So i ran the code about 50 times and each time it returned olg / 1 so What is wrong所以我运行代码大约 50 次,每次它返回 olg / 1 所以出了什么问题

alert("welcome to word unscrambler undscramble this")
console.log("i am not a distraction")
document.write("i am not a distraction either")
var r = ["pttoao","recme","logd","teey","olg"]
var g=Math.floor(Math.random() *+ 6);

if (g=="0") {select =("pttoao")}
  else if(g=="1"){select=("recme")}
   else if (g==2){select="logd"}
   else if(g==3){select="dre"}
    else if(g==4){select="olg"}
if(select=="pttoao"){realword="potato"}
if(select=="recme"){realword="creme"}
if(select=="logd"){realword="gold"}
if(select=="teey"){realword="yeet"}
if(select="olg"){realword="log"}
var awnser= prompt("unscramble "+select)
if(awnser==realword){alert("correct")
}else{
  alert("incorrect")}

maybe it is that it cant randomly select words也许是它不能随机 select 字

Here's some code that works for any amount of words.这是一些适用于任意数量单词的代码。
Notice the structure: array of objects, objects have the real word and the scramble of it.注意结构:对象数组,对象有真实的单词和它的混乱。
The random is relative to the amount of words. random是相对于字数的。
I've combined the prompt, the check, and the alert into one line.我已将提示、检查和警报合并为一行。
"Simplify by complication...":) “通过复杂化来简化......”:)

 var words=[ {real:"potato", scrambled:"pttoao"}, {real:"creme", scrambled:"recme"}, {real:"gold", scrambled:"logd"}, {real:"yeet", scrambled:"teey"}, {real:"log", scrambled:"olg"} ]; var random=Math.floor(Math.random()*words.length); alert( prompt("Unscramble: "+words[random].scrambled) == words[random].real? "Correct": "Wrong" );

 var g=Math.floor(Math.random() *+ 6 )

should be replaced with following as array elements index starts from zero and array "r" contains 5 elements应替换为以下数组元素索引从零开始,数组“r”包含 5 个元素

 var g=Math.floor(Math.random() * 5);

 if(select="olg"){realword="log"}

here, you have assigned "olg" value to select variable.在这里,您已将“olg”值分配给 select 变量。 Inside "if" condition assignment is simply returning assigned value which is "olg" that makes it true and executes realword="log"在“if”条件赋值中只是返回赋值为“olg”的值,使其为真并执行realword="log"

It should be replaced with它应该替换为

if(select=="olg"){realword="log"}

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

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