0

(请注意,这与我刚才提出的问题相似但不同 - 该问题的解决方案是在调用 Math.Random 时添加括号)

在下面代码的底部,我处理了两手二十一点myhandyourhand然后将手记录到控制台

"I scored a "+myHand.score()+" and you scored a "+ yourHand.score());

但是,我得到的结果是

I scored NaN and you scored a NaN

最初,Card 构造函数中的 getValue 方法传递了一个名为的参数,card但构建 Hand 构造函数的说明说调用 getValue 而不传递参数

this.card1.getValue();

所以我将 getValue 方法更改为采用var number(在 Card 构造函数中)

无论如何,长话短说,无论我做什么,它都会打印出来

I scored NaN and you scored a NaN

而且我不确定我到底哪里出错了。

// Make your card constructor again here, but make sure to use private
// variables!
function Card(num, suit){
    var number = num; 
    var suits = suit;
    this.getSuit = function(){
        return suits; 
    }; 
    this.getNumber = function(){
        return number; 
    };

    this.getValue = function(number){
        if (number > 10){
            return 10; 
        }else if (number === 1){
            return 11; 
        }else{
            return number; 
        }

    };

}

function Hand(){
    this.card1 = deal(); 
    this.card2 = deal(); 

    this.score = function(){
    var score1 = this.card1.getValue();
    var score2 = this.card2.getValue();
    return score1 + score2;
    };

}

// Make a deal function here.  It should return a new card with a suit
// that is a random number from 1 to 4, and a number that is a random
// number between 1 and 13

var deal = function(){
    var suit = Math.floor(Math.random() * 4 + 1);
    var number = Math.floor(Math.random() * 13 + 1);
    return new Card(number, suit); 
}; 


// examples of the deal function in action

var myHand = new Hand();
var yourHand = new Hand();
console.log("I scored a "+myHand.score()+" and you scored a "+ yourHand.score());
4

3 回答 3

2

你的getValue功能是错误的。它应该是:

this.getValue = function() {
  if( this.number>10) return 10;
  if( this.number==1) return 11;
  return this.number;
}

出现问题的提示是您在this.card1.getValue()没有参数的情况下调用,而您this.getValue(number)使用参数进行了定义。

于 2012-08-29T23:57:13.613 回答
1

当您处理 card.getValue() 时,它需要一些输入

this.getValue = function(number){
    if (number > 10){
        return 10; 
    }else if (number === 1){
        return 11; 
    }else{
        return number; 
    }

};

该函数不返回任何内容,从而导致 NaN。要解决此问题,请改用 this.number

于 2012-08-30T00:00:38.510 回答
1

您的 get value 函数接受number参数 this.getValue = function(number)

但是你没有在这里传递值:

var score1 = this.card1.getValue();
var score2 = this.card2.getValue();
于 2012-08-30T00:07:22.700 回答