Javascript/HTML 不会进入除默认值以外的 switch case

标签 javascript html

我的任务是尝试编写 Pig 游戏的代码。我试图让代码使用 switch 语句来确定要遵循的代码块,但它跳过案例 1 和案例 2 并直接转到默认案例。 roll.score 来自这个 Javascript 文件:

function Dice(d1, d2){      //d1 = die 1   d2 = die 2
    this.d1 = d1?d1:parseInt(Math.random()*6 + 1);
    this.d2 = d2?d2:parseInt(Math.random()*6 + 1);
}

Dice.prototype.score = function(){         //d1 = die 1   d2 = die 2
    if(this.d1 == 1 || this.d2 == 1){
        return 1;   //return score 0 for turn
    }else if(this.d1 == 1 && this.d2 == 1){
        return 2;    //return 13 as code to reset score to 0 
    }else
        return parseInt(this.d1 + this.d2);
}

Dice.prototype.toString = function(){
    return "Rolled " + this.d1 + " and " + this.d2;
}

它应该做的是返回 1、2 或 2 加在一起的任何数字。就像我上面提到的,无论 roll.score() 返回什么,switch 语句总是转到默认情况。

var again = true;
do {
    var roll = new Dice(parseInt(Math.random() * 6 + 1), parseInt(Math.random() * 6 + 1));
    window.alert(roll.toString());           
    turnCounter++;
    switch (roll.score) {
        case 1: // 1 die = 1
            playerScore = roll.score();
            again = false;
            rollCounter++;
            turnCounter++;
            document.write("Enters case 1");
            break;
        case 2: //2 = snake eyes       
            playerTotal = 0;
            playerScore = 0;
            again = false;
            rollCounter++;
            turnCounter++;
            break;
        default:
            playerScore += roll.score();
            rollCounter++;
            displayScore();
            document.write(roll.score() + "<br/>");
            var rollAgain = window.prompt("Do you want to roll again?(Y/N)");
            if (rollAgain.toUpperCase() === "N") {
                again = false;
                playerTotal += playerScore;
                displayScore();
                turnCounter++;
                if (playerScore > highScore)
                   highScore = playerScore;
            }
            break;
     }

     rollCounter++;
}while (again);

最佳答案

switch (roll.score) {switch (roll.score()) {

不同

roll.score 是一个函数,而您想在返回结果上打开结果 (roll.score())。

关于Javascript/HTML 不会进入除默认值以外的 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494881/

相关文章:

javascript - 使用模糊滤镜模糊框阴影会导致 Webkit 浏览器出现奇怪的线条

javascript - 使用 jquery 在同一个地方显示元素

javascript - 使用 ngSanatize 的 HTML5 音频和 Angular 双向绑定(bind)问题

javascript - React 函数 - 页面加载时更改 url

javascript - 需要 js 中的正则表达式示例

javascript - 如何更新 Mongoose 模型数组?

javascript - Nodejs node-schedule npm 抛出错误 "this.job.execute is not a function"

javascript - css/html/js中如何排列半圆的元素

html - 使页面 curl 的透明图像与纯色背景一起使用

html - 如何将我的图标放在我的 div 的中间和中心?