JavaScript读取JSON报Uncaught TypeError '6'未定义问题求解
问题原因
- 首先你混淆了报错的触发位置:报错根本没走到读取
name属性那一步,是更早的cardsInfo[randomFirstValue]调用失败了。
JS中数组本质是特殊对象,数字索引会被隐式转为字符串类型的属性名,你调用cardsInfo[6]本质是读取cardsInfo的'6'属性,所以控制台会提示「Cannot read property '6' of undefined」——那次随机生成的randomFirstValue刚好是6,而此时cardsInfo本身是undefined。 - 为什么
cardsInfo会是undefined?XMLHttpRequest的onreadystatechange事件会在readyState变化时触发多次,readyState取值从0到4,只有当readyState == 4且请求状态码为200时,你才给cardsInfo赋值。但你把后续操作DOM的for循环写在了这个判断分支外面,所以在readyState为1、2、3的几次事件触发时,代码都会执行for循环,此时cardsInfo还没被赋值,自然会报错。 - 为什么功能看起来正常?
等到readyState变为4、请求成功的那次事件触发时,cardsInfo已经被正确赋值,这次的for循环能正常执行、渲染DOM元素,前面几次的报错不会中断这次正确执行,所以你会看到功能正常但控制台有报错。
修复方案
把所有依赖cardsInfo的逻辑都挪到请求成功的判断分支内部即可,修改后代码如下:
const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var cardsInfo = JSON.parse(xhttp.responseText); // 所有依赖cardsInfo的逻辑都挪到这里 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); } } }
内容的提问来源于stack exchange,提问作者Jank
相关产品推荐
相关产品推荐

