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) {

});
原文地址:https://www.cnblogs.com/sirdong/p/12991225.html