问题描述
未捕获的类型错误:无法读取未定义的属性“6” 在 XMLHttpRequest.xhttp.onreadystatechange (main.js:36) 在 HTMLdivelement。
我正在做一个小游戏来学习和练习 JavaScript,我想获取我存储在 json 文件中的信息,从我显然使用的一组对象的属性中获取信息:{{1} },在我的代码中是 arrayOfObjects[index].propertyOfObject
它工作正常但我收到错误:
未捕获的类型错误:无法读取未定义的属性“6” XMLHttpRequest.xhttp.onreadystatechange (main.js:36) 在 HTMLdivelement。
在浏览器的控制台中,我知道错误意味着什么,但我不明白为什么当 6 是索引,而不是属性,属性是名称时,为什么控制台会显示“无法读取属性 '6'” ,我做错了什么吗?
这是我的代码:
firstNShape.innerHTML = firstShape[randomFirstShape];
这是我的 JSON 文件,它很简单,但我只是为了学习和练习 JSON 以及 JS。
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);
}
}
解决方法
我在 Jazz 的帮助下解决了,我所做的只是将所有逻辑放在 if 语句中,因为如果它在外面,即使条件未完成也会运行,我知道很简单,但我是新手.
,如果它有任何用处,从前,不久前,Bon Jovi 不知道 java 本质上是一个命令行界面,它在 1.1.2 中被加强以包含一个抽象的 Windows 工具包。将 java 视为 CLI 程序,事情会更有意义。 (PS,如果您在大多数 CLI 中键入 reboot,您将改变 ram 的配置方式,而我对放牧山羊一无所知。Gnu 是一个更可取的界面)