Uncaught TypeError: Cannot read property 'forEach' of undefined

js报错 Cannot read property 'forEach' of undefined

数组未定义或者不存在,解决方法:

if (datas && datas.length) {
    datas.forEach(function (item, index) {
        console.log(index);
    })
}

// 或者

if (!datas || !datas.length) return;
datas.forEach(function (item, index) {
    console.log(index);
})

也可以根据实际情况简写为

(datas || []).forEach(function (item) {

});
posted @ 2020-05-30 10:31  sirdong  阅读(8051)  评论(0编辑  收藏  举报