javascripttypeerrorjavascript-objectsgoogle-chrome-console

Console Display Uncaught TypeError


Uncaught TypeError: Cannot read property '6' of undefined at XMLHttpRequest.xhttp.onreadystatechange (main.js:36) at HTMLDivElement.

I'm working on a little game to learn and practice JavaScript, I want to get information that I stored in a json file, to get the information from a property of an array of objects I obviously use: arrayOfObjects[index].propertyOfObject, which in my code is firstNShape.innerHTML = firstShape[randomFirstShape]; it works fine but I get the error:

Uncaught TypeError: Cannot read property '6' of undefined at XMLHttpRequest.xhttp.onreadystatechange (main.js:36) at HTMLDivElement.

in the console of the browser, I know what the error means but I don't understand why the console shows the "Cannot read property '6'" when the 6 it's the index, not a property, the property is name, Am I doing something wrong?

Here is my code:

const xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      var cardsInfo = JSON.parse(xhttp.responseText);
    }

    for (let i = 0; i < 2; i++) {
      //Choose a random value for card
      let randomFirstValue = Math.floor(Math.random() * 13);
      let randomFirstShape = Math.floor(Math.random() * 4);
      let firstShape = ["♥", "♦", "♣", "♠"];

      //create the card
      let firstCard = document.createElement("div");
      firstCard.classList.add("card");
      firstCard.classList.add("cardDisplay");

      //Add value to the card
      let firstNValue = document.createElement("p");
      firstNValue.innerHTML = cardsInfo[randomFirstValue].name;
      firstCard.appendChild(firstNValue);

      //Add shape to the card
      let firstNShape = document.createElement("p");
      firstNShape.innerHTML = firstShape[randomFirstShape];
      firstCard.appendChild(firstNShape);
      //Append card to the card container
      cardContainer.appendChild(firstCard);
    }
}

Here is my JSON file, it's simple but I'm just doing it to learn and practice JSON along with JS.

[
  {
    "name": "A",
    "value": 1,
    "value2": 11
  },
  {
    "name": "2",
    "value": 2
  },
  {
    "name": "3",
    "value": 3
  },
  {
    "name": "4",
    "value": 4
  },
  {
    "name": "5",
    "value": 5
  },
  {
    "name": "6",
    "value": 6
  },
  {
    "name": "7",
    "value": 7
  },
  {
    "name": "8",
    "value": 8
  },
  {
    "name": "9",
    "value": 9
  },
  {
    "name": "10",
    "value": 10
  },
  {
    "name": "J",
    "value": 10
  },
  {
    "name": "Q",
    "value": 10
  },
  {
    "name": "K",
    "value": 10
  }
]


Solution

  • I solved with help of Jazz, all I did is put all the logic inside of the if statement, since if it is outside it will run even if the condition is not completed, I know is so simple but I'm new.