简体   繁体   中英

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

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

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.
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

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

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

here, you have assigned "olg" value to select variable. Inside "if" condition assignment is simply returning assigned value which is "olg" that makes it true and executes realword="log"

It should be replaced with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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