【前端报错】Uncaught TypeError: Cannot read property'变量名' of undefined

这只是多给大家一种解bug思路,通常undefined错就是用了一个没有定义的变量,也引申到下面这种情况:

一、现状说明

  1. 变量名定义正常;
  2. 数据成功渲染到前端;
  3. 但是一直报错Uncaught TypeError: Cannot read property' 变量名' of undefined

二、代码说明

用js遍历json数据渲染到前端。

1、html代码

2、js代码

var goods = document.querySelector(".goods");

function init_goods() {
    alert(infos.length)
    for (var i=0; i <= infos.length; i++) {
        goods.innerHTML += `
    `;
    }
}
init_goods();

3、一部分js数据

var infos = [{"tag": "创业知识", "img_link": "https://static-image.xfz.cn/1563171621_723.png-course.list.small",
    "title": "创业CEO如何避免技术决策错误", "authord": "龚世海 / HiCTO创始人兼CEO", "price": "免费", "len": "免费"},
    {"tag": " 明星案例", "img_link": "https://static-image.xfz.cn/1563171954_878.png-course.list.small",
        "title": "面对危机公关,多快算快", "authord": "高超 / 资深品牌公关", "price": "免费", "len": "免费"},
    {"tag": " 明星案例", "img_link": "https://static-image.xfz.cn/1563171942_636.png-course.list.small",
        "title": "掌握正确的危机公关态度", "authord": "高超 / 资深品牌公关", "price": "免费", "len": "免费"},
    {"tag": " 明星案例", "img_link": "https://static-image.xfz.cn/1563171930_300.png-course.list.small",
        "title": "公关需要对营销“尺度”进行把控", "authord": "高超 / 资深品牌公关", "price": "免费", "len": "免费"},];

三、错误原因

js代码第五行for循环里面,从0开始遍历不能遍历到infos.length。前端报错有点奇妙,正常应该报错index is out of range而不是报错' 变量名' of undefined,有点不明觉厉。所以改成:

for (var i=0; i < infos.length; i++)

-------------------2019.9.21更新--------------------

在我那天改完错的时候第二天早晨等公交车的时候把问题想明白了。

在js中所有没有定义的变量都是undefined,而infos[infos.length]并不存在,所以它就是undefined类型,所以报这个错误很正常。

四、总结

前端是报错没有定义也可能是循环超出下标的原因。

你可能感兴趣的:(前端)