js - cannot set property xxx of undefined

js - cannot set property xxx of undefined

users.bucketList = [];
var td_id=0
var bucket = users.bucketList[td_id];
if (bucket == null || bucket == '' || bucket == 'undefined'){
    // users.bucketList[td_id] = {};
    users.bucketList[td_id].seads = [];
    var slottime = {};
    users.bucketList[td_id].seads.push(slottime);
}

这段js会发生这样的错误:

cannot set property xxx of undefined

原因

因为users.bucketList[td_id]可能是undefined,如果再给users.bucketList[td_id]动态添加属性的话就会报这样的错误

解决方案

users.bucketList[td_id]undefined的时候给它初始化,即users.bucketList[td_id] = {}

猜你喜欢

转载自blog.csdn.net/u013887008/article/details/81025619