-2

我在下面的代码中遇到了一些麻烦,基本上我只是在练习循环并考虑制作一个小游戏来刷新......但是我有点难为为什么 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!");
4

3 回答 3

7

您正在使用||OR 运算符。

鉴于此代码:

(playerWeapon != 'sword' || playerWeapon != 'dagger' || playerWeapon != 'crossbow')

任何词(如“猫”)显然不会是这三个词之一。你应该&&改用。

我不确定== ""测试的目的是什么,但如果要求是这三种武器之一,那么你不需要测试空字符串。

于 2013-05-21T15:46:11.710 回答
1

while ((playerweapon == '') && (the rest of the line means nothing because playerweapon has no value))

你的第一个测试是 playerweapon == '' (nothing) 然后你测试它不等于其他一些值。没有意义,如果它是空白的,它就是空白的

该行应该是

while(playerWeapon != 'sword' && playerWeapon != 'dagger' && playerWeapon != 'crossbow') {

于 2013-05-21T15:46:14.630 回答
0

查看您的 while 条件:

(playerWeapon == '')

playerWeapon = 'cat'它评估为false并且false && (...)总是false如此时,它会打破循环。您需要交换您对 &&s 和 ||s 的使用以使该条件起作用。尝试在纸上手动评估它,原因应该很明显。

于 2013-05-21T15:48:02.467 回答