【发布时间】:2019-06-02 19:25:23
【问题描述】:
我是 JS 新手(第一周),我在为一个学校项目做一个命令行纸牌游戏。我已经能够完成前三个练习(2 和 3 已省略)。
但是,我不明白为什么我无法从deck 访问属性value
我已经四处寻找解决方案,包括这里:
堆栈溢出:compare two numeric String values
中(没有关于比较卡片的内容。PT2 包含我们没有做的 HTML。):https://medium.com/@pakastin/javascript-playing-cards-part-1-ranks-and-values-a9c2368aedbd
Stack Overflow(这个问题被否决了):How to compare 2 cards in a JavaScript card game
我能够搭建套牌(练习 1):
function buildDeck() {
const suits = ['spades', 'hearts', 'diamonds', 'clubs'];
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const deck = [];
for (let r = 0; r < ranks.length; r++) {
for (let s = 0; s < suits.length; s++) {
deck.push({ ranks: ranks[r], suits: suits[s], value: r + 1 });
}
}
return deck;
}
console.log(buildDeck())
这将返回每张卡的 ranks、suits 和 value。
接下来,我尝试解决比对卡片的问题(练习4):
const compare = (firstCard, secondCard) => {
const cardValue = firstCard.value - secondCard.value;
return cardValue;
}
console.log(compare());
但是,当我尝试返回第一张卡减去第二张卡的 value 属性时,出现以下错误:
const cardValue = firstCard.value - secondCard.value;
TypeError: Cannot read property 'value' of undefined
如果我从代码中删除.value,我当然会得到NaN,因为数组中没有可与之比较的对象。
我被困在这一点上,不知道如何获得卡片之间的差异。非常感谢任何建议/帮助。
【问题讨论】:
标签: javascript arrays