Javascript switch statement not working - is three too many?
本问题已经有最佳答案,请猛点这里访问。
我对javascript还不熟悉,我正在尝试通过制作一个小程序来学习,在这个程序中,你可以进入你的占星术符号、行星和房子,来制作一个有点疯狂的故事。为此,我在一个函数中放入了三个switch语句。
不确定这是否是太多的switch语句,但是,当我在chrome上加载它时,有时我只得到文本,有时我得到文本和text2,有时我只得到text3。
有人知道这是为什么吗?一个函数中的switch语句是否太多?我在网上搜索,但找不到一个函数允许有多少个。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | function tellMeaStory() { var text; var text2; var text3; var sign = document.getElementById("mySign").value; var planet = document.getElementById("myPlanet").value; var house = document.getElementById("myHouse").value; switch(sign) { case"Aries","aries": text ="red"; break; case"Taurus","taurus": text ="calm"; break; case"Gemini","gemini": text ="quirky"; break; case"Cancer","cancer": text ="moody"; break; case"Leo","leo": text ="hungry"; break; default: text ="sign"; } switch(planet) { case"Sun","sun": text2 ="hero"; break; case"Moon","moon": text2 ="mother"; break; case"Mercury","mercury": text2 ="twin"; break; case"Venus","venus": text2 ="courtesan"; break; case"Mars","mars": text2 ="soldier"; break; default: text2 ="planet"; } switch(house) { case"one","One": text3 ="hole"; break; case"two","Two": text3 ="buffet"; break; case"three","Three": text3 ="database"; break; case"four","Four": text3 ="stomach"; break; case"five","Five": text3 ="wilderness"; break; default: text3 ="house"; } document.getElementById("demo").innerHTML +="You are a" + text +"" + text2 +" in a" + text3; } |
1 2 3 4 5 | <input id="mySign" type="text" value="Enter your sign"> <input id="myPlanet" type="text" value="Enter your planet"> <input id="myHouse" type="text" value="Enter your house"> <button onclick="tellMeaStory()">Generate</button> |
你看到奇怪结果的原因是因为javascript处理逗号的方式。例如,
撤销你的交换声明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | switch(true) { case (planet.toUpperCase() ==="SUN"): text2 ="hero"; break; case (planet.toUpperCase() ==="MOON"): text2 ="mother"; break; case (planet.toUpperCase() ==="MERCURY"): text2 ="twin"; break; case (planet.toUpperCase() ==="Venus"): text2 ="courtesan"; break; case (planet.toUpperCase() ==="MARS"): text2 ="soldier"; break; default: text2 ="planet"; } |
或者您可以使用一系列if语句,一起跳过开关。
1 2 3 | if(planet ==="sun" || planet ==="Sun" || planet ==="SUn") { // text assignment } |
或
1 2 3 | if (planet.toLowerCase() ==="sun") { // text assignment } |
您可以在这里了解更多关于逗号运算符的信息。