循环后函数在对象中返回未定义的值

时间:2018-12-20 22:20:46

标签: javascript

我目前正在做我的第一个JS项目,一个BlackJack游戏。我已经编写了一个用于创建牌组的函数,牌组是包含卡片的西服,价值和重量的一系列对象。 至于权重,循环后该函数返回未定义的值,则返回Suit和Value。这是我的代码:

// Creation of the deck
function deckCreate() {
  for (let i = 0; i < cardSuits.length; i++) {
    for (let j = 0; j < cardValues.length; j++) {
      let cardWeight = parseInt(cardValues[j]);
      if (cardValues[j] === "J" || cardValues[j] === "Q" || cardValues[j] === "K") {
        cardWeight = 10;
      } if (cardValues[j] === "A") {
        cardWeight = 11;
      }
      let card = {
        Suit: cardSuits[i],
        Value: cardValues[j],
        Weight: cardWeight[j]
      }; deck.push(card);
    }
  } return deck;
}

之前,我创建了以下变量:

const cardSuits = ["&clubs;", "&hearts;", "&diams;", "&spades;"];
const cardValues = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
let deck = [];

返回的对象是: 例如

0: {Suit: "&spades;", Value: "2", Weight: undefined}
1: {Suit: "&hearts;", Value: "10", Weight: undefined}
2: {Suit: "&clubs;", Value: "5", Weight: undefined}

我似乎无法理解为什么权重未定义。 希望有帮助 谢谢!

3 个答案:

答案 0 :(得分:2)

已更正,删除了[j]

// Creation of the deck
function deckCreate() {
  for (let i = 0; i < cardSuits.length; i++) {
    for (let j = 0; j < cardValues.length; j++) {
      let cardWeight = parseInt(cardValues[j]);
      if (cardValues[j] === "J" || cardValues[j] === "Q" || cardValues[j] === "K") {
        cardWeight = 10;
      } if (cardValues[j] === "A") {
        cardWeight = 11;
      }
      let card = {
        Suit: cardSuits[i],
        Value: cardValues[j],
        Weight: cardWeight
      }; deck.push(card);
    }
  } return deck;
}

const cardSuits = ["&clubs;", "&hearts;", "&diams;", "&spades;"];
const cardValues = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
var deck = [];

console.log(deckCreate());

答案 1 :(得分:2)

cardWeight是一个数字,而不是一个数组,您可以从下面这行得到它:

// You are pulling a single value from an array here:
let cardWeight = parseInt(cardValues[j]);

因此,当您尝试向其传递索引时,将返回undefined。只需将cardWeight作为单个值访问即可:

// Creation of the deck
let cardSuits = ["&Clubs", "&Spades", "&Diamonds", "&Hearts"];
let cardValues = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"];
let deck = [];

function deckCreate() {
  for (let i = 0; i < cardSuits.length; i++) {
    for (let j = 0; j < cardValues.length; j++) {
      let cardWeight = parseInt(cardValues[j]);
      if (cardValues[j] === "J" || cardValues[j] === "Q" || cardValues[j] === "K") {
        cardWeight = 10;
      } if (cardValues[j] === "A") {
        cardWeight = 11;
      }
      let card = {
        Suit: cardSuits[i],
        Value: cardValues[j],
        Weight: cardWeight // <-- This is a single value, not an array
      }; deck.push(card);
    }
  } return deck;
}

console.log(deckCreate());

答案 2 :(得分:1)

Weight: cardWeight[j]更改为Weight: cardWeight