当调用loadGame()
函数时,它应该构建一副牌,发牌,然后展示牌。它除了完成这一切之外,还提供更多功能。当向用户显示卡片的函数运行时,它会输出代表卡片的编号以及整个页面上唯一原型(prototype)的代码。为什么?
Javascipt 的一部分
//Variables
var theDeck = new Array();
var discardPile = new Array();
var allHands = new Array();
//Prototypes
Array.prototype.exists = function(search) {
for(i=0;i<this.length;i++)
if (this[i] == search) return true;
return false;
}
//Functions (Only the ones the that are needed for this question)
function buildDeck() {
var i = 0
for (x=0;x<=3;x++) {
for (y=0;y<=12;y++) {
//x is for the type (i.e. spades, hearts, ...)
//y is for the face value (i.e. nine, ten, jack, ...)
theDeck[i] = new Array(x,y);
i++ //Gets ready to add the next card in the deck.
}
}
}
function dealHands() {
var cardsOfHand = new Array()
for (x=0;x<=1;x++) {
for (y=0;y<=1;y++) {
allHands[x][y] = fetchCard();
discardCard(allHands[x][y]);
}
}
}
function discardCard(card) {
var totalCards = discardPile.length;
if (totalCard != 0) { totalCards++ }
discardPile[totalCards] = card;
}
function fetchCard() {
var usedCard = true;
while(usedCard == true) {
var randomCard = Math.floor(Math.random()*51);
usedCard = discardPile.exists(randomCard);
}
return randomCard;
}
function showHands() {
for (whoHand in allHands) {
var hand = allHands[whoHand];
var cards = "";
for (whichCard in hand) {
var card = hand[whichCard];
cards += "[" + card + "]"; //TEMP: Used for debugging.
}
id = "player" + whoHand + "cards";
document.getElementById(id).innerHTML = cards;
}
}
function loadGame() {
buildDeck();
dealHands();
showHands();
}
HTML 的一部分
<fieldset>
<legend align="center">Dealer's Hand</legend>
<div id="player0cards"></div>
</fieldset>
<fieldset id="">
<legend align="center">Player's Hand</legend>
<div id="player1cards"></div>
</fieldset>
输出
带有“player0cards”ID 的 Div 元素:[50][12][function (search) { for(i=0;i
带“player1cards”ID 的 Div 元素:[14][6][function (search) { for(i=0;i
注意:数字(即 50、12、14、6)是代表一张卡片的随机数。
为什么整个脚本中的唯一原型(prototype)会出现另一部分?
错误
未捕获类型错误:无法在
循环。for (whoHand in allHands)
的结束 }
行上设置 null 属性“innerHTML”
最佳答案
看起来问题是您使用 for-in 语法运行原生 JS 数组。此语法适用于对象,如果将其用于 native 数组,它也会返回成员/方法,就像函数“exists”一样。
仅使用for(var i=0;i<array.length;++i)
- 迭代数组项的语法。
关于javascript - 运行函数时出现意外输出。输出原型(prototype)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5162156/