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] = {}