我正在一個簡單的二十一點程序上工作。我對javascript完全陌生,無法調試我的程序。我一直得到TypeError:無法調用未定義的getNumber方法.....我完全失去了。我正在嘗試爲每張卡片獲取存儲的數值,但看起來該錯誤發生在Hand
類中的printHand()
方法中。當打印出兩張或更多牌的牌時,我通過每手牌中的每張牌循環調用cards[i].getNumber()
,其中cards[]
是每手牌中的牌陣列。我沒有正確引用卡片[]嗎?我仔細檢查,以確保我的方法和變量設置爲public,但我仍然不知道爲什麼getNumber()
正在一個未定義的對象上被調用。我引用這個對象的方式有什麼問題嗎?獲取TypeError:無法調用getNumber方法的undefined
這裏是我的代碼:
// Card Constructor
function Card (suit, number){
var the_suit = suit;
var the_number = number;
this.getNumber = function(){
return the_number;
};
this.getSuit = function(){
return the_suit;
};
this.getValue = function(){
// face cards
if(the_number > 10){
return 10;
// aces
} else if (the_number < 2){
return 11;
// other cards
} else {
return the_number;
}
};
}
function deal(){
// get card suit
var rand1 = Math.floor(Math.random () * 4 + 1);
// get car number
var rand2 = Math.floor(Math.random () * 13 + 1);
var newCard = new Card(rand1, rand2);
}
function Hand(){
// create two cards for initial hand
var card1 = deal();
var card2 = deal();
// store cards in array
var cards = [card1,card2];
// getter
this.getHand = function(){
return cards;
};
// get the score
this.score = function(){
var length = cards.length;
var score = 0;
var numAces = 0;
for(i = 0; i < length; i++){
if (cards[i].getValue() === 11){
numAces++;
}
score += cards[i].getValue();
}
while(score > 21 && numAces !== 0){
sum -= 10;
numAces--;
}
};
this.printHand = function(){
var length = cards.length;
for(i=0; i< length; i++){
var string = string + cards[i].getNumber() + " of suit " + cards[i].getSuit() + ", ";
}
return string;
};
this.hitMe = function(){
var newCard = deal();
cards.push(newCard);
}
}
function playAsDealer(){
var newHand = new Hand();
while(newHand.score < 17){
newHand.hitMe();
}
return newHand;
}
function playAsUser(){
var newHand = new Hand();
var choice = confirm("Current hand: "+ newHand.printHand() + ": Hold (Ok) or Stand(Cancel)");
while(choice){
newHand.hitMe();
choice = confirm("Current hand: "+ newHand.printHand() + ": Hold (Ok) or Stand(Cancel)");
}
}
function declareWinner(user, dealer){
//user wins case
if (user.score > dealer.score){
console.log("You are the Champion!");
}
// tie game
else if(user.score===dealer.score){
console.log("Tied!");
}
else{
console.log("Loser!!");
}
}
function playGame(){
var user = playAsUser();
var dealer = playAsDealer();
console.log("User's Hand: " + user.printHand());
console.log("Dealer's Hand: " + dealer.printHand());
declareWinner();
}
playGame();
對於「playAsUser」和發送變量以聲明reWinner(用戶,經銷商); – Adidi 2013-03-20 01:08:27
非常感謝你....這幫了我很多! – accraze 2013-03-20 01:59:09