我对下面的代码有点麻烦,基本上我只是练习循环,并考虑制作一个小游戏来刷...但是我有点难过为什么while循环正在通过一个例如“cat”或“hgh”这样的条目,因此最后要警惕说出一大堆胡言乱语......
var playerWeapon = prompt("Before you go to slay the Dragon, please choose your weapon from the following... \n\n1.) Sword \n2.) Crossbow\n3.) Dagger").toLowerCase();
while( (playerWeapon == '' ) && (playerWeapon != 'sword' || playerWeapon != 'dagger' || playerWeapon != 'crossbow') ){
alert("We need you to pick a weapon...");
var playerWeapon = prompt("Sorry, you need to chose a valid weapon...what will it be? \n\n1.) Sword \n2.) Crossbow\n3.) Dagger").toLowerCase();
}
var weaponStrength = '';
if(playerWeapon == "sword"){
var weaponStrength = 10;
}
if(playerWeapon == "dagger"){
var weaponStrength = 7;
}
if(playerWeapon == "crossbow"){
var weaponStrength = 4;
}
alert("Excellent, the " + playerWeapon + " is a fine choice and your weapon is " + weaponStrength + " strong...now lets go!");
答案 0 :(得分:6)
您正在使用||
OR运算符。
鉴于此代码:
(playerWeapon != 'sword' || playerWeapon != 'dagger' || playerWeapon != 'crossbow')
任何单词(如“cat”)显然不会是这三个中的一个。您应该使用&&
代替。
我不确定== ""
测试的目的是什么,但如果要求是这三种武器中的一种,那么你就不需要测试一个空字符串。
答案 1 :(得分:1)
while ((playerweapon == '') && (the rest of the line means nothing because playerweapon has no value))
你的第一个测试是playerweapon ==''(没有),然后你测试它不等于其他一些值。没有意义,如果它是空白的,那就是空白
该行应为
while(playerWeapon != 'sword' && playerWeapon != 'dagger' && playerWeapon != 'crossbow') {
答案 2 :(得分:0)
看看你的状况:
(playerWeapon == '')
评估为playerWeapon = 'cat'
且false
的{{1}}始终为false && (...)
,因此会打破循环。您需要交换使用&& s和|| s来使条件有效。尝试在纸上手工评估它,这应该是显而易见的原因。