JavaScript:返回NaN(第2部分)

时间:2012-08-29 23:53:16

标签: javascript

(注意这与我刚才提出的问题类似但不一样 - 该问题的解决方案是在调用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());

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

当你发现card.getValue()时,它需要一些输入

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

};

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

答案 2 :(得分:1)

您的获取值函数接受number参数     this.getValue = function(number)

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

var score1 = this.card1.getValue();
var score2 = this.card2.getValue();